如何释放 fileinputstream 和 fileoutstream 的资源?

How do I releasing resources for fileinputstream and fileoutstream?

在我的 veracode 扫描中,我的漏洞很低:资源关闭不当或释放 CWE ID 404

这是我的代码:

public static boolean nioCopy(File source, File destination) {
      boolean retval = false;
      
      FileChannel inChannel = null, outChannel = null;
      
      try {
          inChannel = (new FileInputStream(source)).getChannel();
          outChannel = (new FileOutputStream(destination)).getChannel();
          
          long size = inChannel.size();
          long position = 0;
          while ( position < size )
          {
             position += inChannel.transferTo( position, WINDOWS_MAGIC_BUFFER_SIZE, outChannel );
          }
          retval = true;
      } catch (FileNotFoundException e) {
          e.printStackTrace();
          retval = false;
      } catch (IOException e) {
          e.printStackTrace();
          retval = false;
      } finally {
          try {
              if (inChannel != null) {
                  inChannel.close();
              }
              
              if (outChannel != null) {
                  outChannel.close();
              }
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
      
      return retval;
  }

Veracode 特别指向这一行:

outChannel = (new FileOutputStream(destination)).getChannel();

但是,我相信我会在 finally 块中释放资源。我指的是这个 link:http://javaelegance.blogspot.com/2015/10/improper-resource-shutdown-or-release.html

我做错了什么?

假设 Java 8 或更高,使用 try with resources 语句。参见 https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html。它基本上会为您处理自动关闭可关闭对象。

try (inChannel = (new FileInputStream(source)).getChannel()) {
    //Use inChannel
}
catch(IOException ex) {
    //Handle exception
}