java file in/out 标准写法及注解

  InputStream in = null;  
  OutputStream out = null; 
  try {  
        //多态应用,FileInputStream继承InputStream  
         in = new FileInputStream(src);
       //多态应用,FileOutputStream继承OutputStream  
         out = new FileOutputStream(des);
        //申请1M内存,用于存放读入的数据,其实是作为缓冲(cache)  
         byte[] buf = new byte[1024];
        /**
          * cread(buf))指将数据先读入buf内,
          * 当buf满时,跳出read方法,并返回buf的容量,
          * 然后赋值给n;当buf不满但已经读取完毕就返回buf的实际存放字节数  
          * 涉及到不用资源时,先释放资源再赋值null这样使得垃圾回收更快  
          **/
         int n ;  
         while((n = in.read(buf))> 0){
              out.write(buf, 0, n);  
         }  
  } catch (FileNotFoundException e) {  
          e.printStackTrace();  
  } catch (IOException e) {  
          e.printStackTrace();  
  }finally{  
         try {  
               /**
                * close()方法本身就有可能抛出异常,故而用try catch 包裹;
                * 如果抛出异常in就不能正常关闭但是资源还被占用,故而在finally里 in=null;  
                * 无论抛出异常与否都将in赋值null,这样有利于垃圾回收机制将其回收;我其实挺建议这样写 
                * 涉及到不用资源时,先释放资源再赋值null这样使得垃圾回收更快  
                **/
                in.close();       
                out.close();  
         } catch (IOException e) {  
                e.printStackTrace();  
         }finally{  
                in = null;  
                out = null;  
         }  
  }  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容