黑马程序员技术交流社区
标题:
Java的IO操作中关闭流的注意点
[打印本页]
作者:
稀饭酱紫
时间:
2015-12-20 19:03
标题:
Java的IO操作中关闭流的注意点
// 一、错误示例1
public void CopyFile() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt"); // ①
fw = new FileWriter("c:\\xy2.txt"); // ②
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
throw new RuntimeException("文件拷贝操作失败");
} finally {
try {
fr.close(); // ③
fw.close(); // ④
} catch (IOException e) {
throw new RuntimeException("关闭失败");
}
}
}
/*
* 若①中代码出错,fr根本就没有初始化,执行③的时候就会报空指针异常。②④同样是这个道理。
*
*
* 二、错误示例2
*/
public void CopyFile1() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt"); // ①
fw = new FileWriter("c:\\xy2.txt"); // ②
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
throw new RuntimeException("文件拷贝操作失败");
} finally {
try {
if (null != fr) {
fr.close(); // ③
}
if (null != fw) {
fw.close(); // ④
}
} catch (IOException e) {
throw new RuntimeException("关闭失败"); // ⑤
}
}
}
/*
* 加上是否为空的判断可以避免空指针异常。但是如果③执行出错,程序会直接进入⑤而④根本没有得到执行,导致无法关闭。
*
* 三、正确示例
*/
public void CopyFile2() {
FileReader fr = null;
FileWriter fw = null;
try {
fr = new FileReader("c:\\xy1.txt");
fw = new FileWriter("c:\\xy2.txt");
char[] charBuffer = new char[1024];
int len = 0;
while ((len = fr.read(charBuffer)) != -1) {
fw.write(charBuffer, 0, len);
}
System.out.println("文件复制成功");
} catch (IOException e) {
throw new RuntimeException("文件拷贝操作失败");
} finally {
try {
if (null != fr) {
fr.close();
}
} catch (IOException e) {
throw new RuntimeException("关闭失败");
}
try {
if (null != fw) {
fw.close();
}
} catch (IOException e) {
throw new RuntimeException("关闭失败");
}
}
}
作者:
孜孜不倦
时间:
2015-12-21 19:22
赞一个。
作者:
安先森
时间:
2015-12-21 21:03
赞一个。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2