调用IO输出流的close的close方法时会先调用flush方法再调用close方法(这是我在练习IO时发现的,当时我没有flush,用完流后也没有close,这当然不是好的编程习惯了)
可以通过下面的例子来证明
/*
通过FileReader和FileWriter类实现文件的复制
*/
import java.io.*;
public class TestFileReader {
public static void main(String[] args){
FileReader fr = null;
FileWriter fw = null;
int c;
try {
fr = new FileReader("D:\\SourceCode \\HelloWorld.java");
fw = new FileWriter("D:\\SourceCode\\HelloWorld.bak");
while((c=fr.read()) != -1) {
fw.write(c);
}
//fw.flush();
} catch(FileNotFoundException e){
System.out.println("文件没有找到");
System.exit(-1);
} catch(IOException e1) {
System.out.println("读取文件发生错误");
System.exit(-1);
} finally {
try {
fr.close();
//fw.close();
} catch(IOException e3) {
System.out.println("请查看其他相应错误");
System.exit(-1);
}
}
}
}
说明:不调用flush或close方法HelloWorld.bak文件的内容为空
若调用flush或close方法HelloWorld.bak文件的内容为HelloWorld.java的内容
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7419833/viewspace-613583/ ,如需转载,请注明出处,否则将追究法律责任。