续上篇,完成了复制一jpg文件的时候还有一处问题,就是代码运行过程中,可能会抛出异常,程序可能会终止,这样close操作就会运行不到
从而可能导致文件资源泄露.那么我们应该使用try{}catch{}语句块来包裹之前的语句.
所以对上篇结尾的代码就需要改进
得到:
private static void copyFile(String srcPath, String destPath) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try{
fileInputStream = new FileInputStream(srcPath);
fileOutputStream = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int len = -1;
while((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer,0, len);
}
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但是改进后的代码也有问题,如果输入流对象和输出流对象在初始化时就抛出了异常,那么两个变量就指向空,直接执行finally中代码就会发生空指针异常
所以仍需改进为:
private static void copyFile(String srcPath, String destPath) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try{
fileInputStream = new FileInputStream(srcPath);
fileOutputStream = new FileOutputStream(destPath);
byte[] buffer = new byte[1024];
int len = -1;
while((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer,0, len);
}
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
if(fileInputStream != null) {
fileInputStream.close();
}
if(fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
改进之后代码没有太大问题了,但是非常不美观,嵌套语句太多,看起来复杂,所以还有最后这种写法
private static void copyFile2(String srcPath, String destPath) {
try(FileInputStream fileInputStream = new FileInputStream(srcPath);
FileOutputStream fileOutputStream = new FileOutputStream(destPath)
){
byte[] buffer = new byte[1024];
int len = -1;
while((len = fileInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer,0, len);
}
}catch (IOException e) {
e.printStackTrace();
}
}
改写后的copyFile方法就更加美观了
写成这样就不需要再显示调用close方法,自动调用并处理,但是前提是这个类必须要实现Closable接口.