先看这种写法:
public static void main(String[] args) throws IOException { try { FileReader r = new FileReader("d:/ti.txt"); StringBuilder sb = new StringBuilder(); char[] temp = new char[1]; int read = r.read(temp); while(read!=-1){ sb.append(temp); } String strAfter = sb.toString().replace("c", "x"); FileWriter w = new FileWriter("d:/titi.txt"); w.write(strAfter); r.close(); w.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
debug:
read为1所以while就成了无限循环,内存溢出了
当这样修改后:
public static void main(String[] args) throws IOException { try { FileReader r = new FileReader("d:/ti.txt"); StringBuilder sb = new StringBuilder(); char[] temp = new char[1]; //r.read(temp)放到while的里 while((r.read(temp))!=-1){ sb.append(temp); } String strAfter = sb.toString().replace("c", "x"); FileWriter w = new FileWriter("d:/titi.txt"); w.write(strAfter); r.close(); w.close(); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } }
所以,要一直取一直取一直取的应该放在while里,不能放while外
时间: 2024-10-20 04:02:06