黑马程序员技术交流社区

标题: 关于IO流的关闭 [打印本页]

作者: 杨玉揆    时间: 2011-12-10 12:33
标题: 关于IO流的关闭
本帖最后由 杨玉揆 于 2011-12-10 12:58 编辑

不知道大家有没有考虑过关于文件之间的拷贝,对于先关那个流对象的问题?是先关读取流(fis.close())还是先关写入流(fos.close())呢?还是先关闭那个都一样?
  1. import java.io.*;
  2. class  PictureStream1
  3. {
  4.         public static void main(String[] args)
  5.         {
  6.                 FileOutputStream fos = null;
  7.                        
  8.                 FileInputStream fis = null;
  9.                        
  10.                 try
  11.                 {
  12.                         fos = new FileOutputStream("1.png");
  13.                         fis =new FileInputStream("Iterator.png");
  14.                         byte[] buf = new byte[1024];
  15.                         int len = 0;
  16.                         while((len = fis.read(buf))!= -1)
  17.                         {
  18.                                 fos.write(buf);
  19.                         }
  20.                 }
  21.                 catch (IOException e)
  22.                 {
  23.                         throw new RuntimeException("读取失败");
  24.                 }
  25.                 finally
  26.                 {
  27.                         try
  28.                         {
  29.                                 if(fos!=null)
  30.                                         fos.close();
  31.                         }
  32.                         catch (IOException e)
  33.                         {
  34.                                 throw new RuntimeException("关闭资源失败");
  35.                         }
  36.                         try
  37.                         {
  38.                                 if(fis!=null)
  39.                                         fis.close();
  40.                         }
  41.                         catch (IOException e)
  42.                         {
  43.                                 throw new RuntimeException("关闭资源失败");
  44.                         }
  45.                        
  46.                                
  47.                 }
  48.         }
  49. }
复制代码
该贴已经同步到 杨玉揆的微博
作者: 李明    时间: 2011-12-10 12:41
应该是一样的,没什么区别,最后只要能全关掉应该就可以了。
作者: 侯伟浩    时间: 2011-12-10 12:51
个人认为应该这样:
  1. <流1>
  2.    <流2>
  3.    </流2>
  4. </流1>
复制代码
不知这么写楼主是否明白
作者: 杨玉揆    时间: 2011-12-10 12:57
嗯 浩哥收到
作者: 李振元    时间: 2011-12-10 13:03
个人认为:先打开的先关闭。






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2