我们在JAVA项目中会处理流,流使用完成后一定要注意关闭流,但是在关闭流时有一些注意点容易忽略,我们以文件流为例先看两个错误实例。
/** * 错误实例1 * * @author 今日头条号「IT徐胖子」 * */public class Test1 {public void copyFile() {FileReader fr = null;FileWriter fw = null;try {fr = new FileReader("c:\aaa.txt"); // 代码1fw = new FileWriter("c:\bbb.txt"); // 代码2char[] 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(); // 代码3fw.close(); // 代码4} catch (IOException e) {throw new RuntimeException("流关闭失败");}}}}
Test1问题在于如果代码1出错,fr根本就没有初始化,执行代码3时就会报空指针异常。代码2和代码4同样是这个道理。
/** * 错误实例2 * * @author 今日头条号「IT徐胖子」 * */public class Test2 {public void copyFile() {FileReader fr = null;FileWriter fw = null;try {fr = new FileReader("c:\aaa.txt"); // 代码1fw = new FileWriter("c:\bbb.txt"); // 代码2char[] 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(); // 代码3}if (null != fw) {fw.close(); // 代码4}} catch (IOException e) {throw new RuntimeException("流关闭失败"); // 代码5}}}}
Test2加上是否为空的判断可以避免空指针异常。但是如果代码3执行出错,程序会直接进入代码5,而代码4根本没有得到执行,导致流无法关闭。我们来看一个正确实例。
/** * 正确实例 * * @author 今日头条号「IT徐胖子」 * */public class Test3 {public void copyFile() {FileReader fr = null;FileWriter fw = null;try {fr = new FileReader("c:\aaa.txt");fw = new FileWriter("c:\bbb.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("流关闭失败");}}}}