Java IO读写的教训之BestPractice

最近在做Dojo+Ajax+Webservice开发,都是基于Log Report for WPC team的模板,遇到了极其挠头的问题。

defect描述:程序不定时不能删除文件夹,程序获取一个list总是增加,怀疑与IO有关。

问题解决:一般来说 java file 失败 有以下几个原因
1.看看是否被别的进程引用,手工删除试试。(就是手工不行!
2.file是文件夹 并且不为空,有别的文件夹或文件。
3.极有可能有可能自己前面没有关闭此文件的流 。

发现自己很多代码都忘记关闭IO流了,faint,导致debug了两天。

以下是常用的IO读写代码,下次拷贝它了

public void writeToFile(String filename) {
 
BufferedWriter bufferedWriter = null;
 
try {
 
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(new FileWriter(filename));
 
//Start writing to the output stream
bufferedWriter.write("Writing line one to file");
bufferedWriter.newLine();
bufferedWriter.write("Writing line two to file");
 
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedWriter
try {
if (bufferedWriter != null) {
bufferedWriter.flush();
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void readFromFile(String filename) {
 
BufferedReader bufferedReader = null;
 
try {
 
//Construct the BufferedReader object
bufferedReader = new BufferedReader(new FileReader(filename));
 
String line = null;
 
while ((line = bufferedReader.readLine()) != null) {
//Process the data, here we just print it out
System.out.println(line);
}
 
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the BufferedReader
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Leave a Comment.