java-文件流正确关闭资源

时间:2021-03-25 06:02:00

用文件流来拷贝一个文件,用到文件字节输入流(FileInputStream)和文件字节输出流(FileOutputStream),用输入流把字节文件读到缓冲数组中,然后将缓冲数组中的字节写到文件中,就很好的完成了文件的复制操作。

来,看一下代码

         //1.创建源和目标
File srcFile = new File("C:/Users/15626/Desktop/test/123.txt");
File targetFile = new File("C:/Users/15626/Desktop/test/123_copy.txt");
//2.创建输入流和输出流
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(targetFile);
//3.输入 输出操作
byte[] buffer = new byte[10];
int len = 0;
while((len = in.read(buffer)) != -1){
//String str = new String(buffer,0,len);
out.write(buffer, 0, len);;
}
//4.关闭资源文件
in.close();
out.close();

完了你会发现出现了

java-文件流正确关闭资源

全是错误,那是因为输出输出可能会出现异常,可能你会直接抛出去,那么怎么正确处理这些异常情况?

当然是try-catch-finally

         FileInputStream in = null;
FileOutputStream out = null;
try{//可能出现问题的代码
//1.创建源和目标
File srcFile = new File("C:/Users/15626/Desktop/test/123.txt");
File targetFile = new File("C:/Users/15626/Desktop/test/123_copy.txt");
//2.创建输入流和输出流
in = new FileInputStream(srcFile);
out = new FileOutputStream(targetFile);
//3.输入 输出操作
byte[] buffer = new byte[10];
int len = 0;
while((len = in.read(buffer)) != -1){
//String str = new String(buffer,0,len);
out.write(buffer, 0, len);;
}
}catch(Exception e){//处理异常
e.printStackTrace();
}finally{
//4.关闭资源文件
try{
in.close();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}

好了,到这里之后异常终于消除了,然而这个程序还是有问题:

  当程序执行到  in = new FileInputStream(srcFile); 的时候,假设有个异常,然后程序后去处理这个异常,根本没有执行下面的程序,然而这时候out还是null,在finally中还关闭了out,本身没有异常,你制造了异常。  那么怎么解决呢?

  那么将它们分开try就ok了:

 

         finally{
//4.关闭资源文件
try{
if(in != null){
in.close();
}
}catch(Exception e){
e.printStackTrace();
}
try{
if(out != null){
out.close();
} }catch(Exception e){
e.printStackTrace();
}
}

到这你会发现程序的主体都在上面,然而下面却处理了这么多异常还有关闭资源,程序变得很难看!然而java7之后,出现了自动关闭资源的机制,我去,这感情好啊,来欣赏一下:

         File srcFile = new File("C:/Users/15626/Desktop/test/123.txt");
File targetFile = new File("C:/Users/15626/Desktop/test/123_copy.txt");
try(//打开资源的代码
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(targetFile);
){
//3.输入 输出操作
byte[] buffer = new byte[10];
int len = 0;
while((len = in.read(buffer)) != -1){
//String str = new String(buffer,0,len);
out.write(buffer, 0, len);;
}
}catch(Exception e){
e.printStackTrace();
}

嗯,这个新特性很好!

 try(打开资源的代码 ){

   可能存在异常的代码

 }catch(){

   处理异常信息

 }