小明写了一段代码,想实现替换文件部分内容的目标,但是代码似乎写得有些问题,请你纠正并优化八戒的代码(请不要在原来的代码上做修改),并给出你的优化逻辑,优化点多多益善。 public static void main(String[] args) throws IOException { File file = new File("some file path"); List list1 = new ArrayList(); FileInputStream fileInputStream = new FileInputStream(file); byte[] bytes = new byte[1024]; int i = fileInputStream.read(bytes); if(i > 0) { do { i = fileInputStream.read(bytes); String s = new String(bytes, 0 , i); list1.add(s); } while(i != -1); } i = fileInputStream.read(bytes); String start = new String(bytes, 0, i); list1.add(start); for (int i1 = 0; i1 < list1.size(); i1++) { String s = (String) list1.get(i1); if(s.contains("1")) { s = s.replace("1", "a"); } else if(s.contains("2")) { s = s.replace("2", "b"); } else if(s.contains("3")) { s = s.replace("3", "c"); } else if(s.contains("4")) { s = s.replace("4", "d"); } list1.remove(i1); list1.add(i1, s); } FileOutputStream fos = new FileOutputStream(file); for (Object o : list1) { fos.write(o.toString().getBytes()); } }
时间: 2023-03-25 08:04:18 浏览: 58
你好,以下是我对小明代码的优化建议:
public static void main(String[] args) throws IOException {
File file = new File("some file path");
List<String> list1 = new ArrayList<>(); // 使用泛型,避免类型转换
try (FileInputStream fileInputStream = new FileInputStream(file)) { // 使用 try-with-resources,避免资源泄漏
byte[] bytes = new byte[1024];
int i;
while ((i = fileInputStream.read(bytes)) != -1) { // 使用 while 循环读取文件内容
String s = new String(bytes, , i);
list1.add(s);
}
}
String start = list1.get(list1.size() - 1); // 直接获取最后一个元素
list1.remove(list1.size() - 1); // 移除最后一个元素
for (int i = ; i < list1.size(); i++) { // 修改循环条件,避免越界
String s = list1.get(i);
s = s.replaceAll("1", "a").replaceAll("2", "b").replaceAll("3", "c").replaceAll("4", "d"); // 使用 replaceAll 方法,一次性替换多个字符
list1.set(i, s); // 直接替换原来的元素
}
try (FileOutputStream fos = new FileOutputStream(file)) { // 使用 try-with-resources,避免资源泄漏
for (String s : list1) { // 使用增强 for 循环
fos.write(s.getBytes());
}
fos.write(start.getBytes()); // 最后写入最后一个元素
}
}
希望对你有帮助!
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)