javafilestreamveracode

How do I releasing resources for fileinputstream and fileoutstream?


In my veracode scan, I have very low vulnerability: Improper Resource Shutdown or Release CWE ID 404

And here is my code:

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 is specifically pointing to this line:

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

However, I believe I am releasing the resource in finally block. I was referring to this link: http://javaelegance.blogspot.com/2015/10/improper-resource-shutdown-or-release.html

What am I doing wrong here?


Solution

  • Assuming Java 8 or higher, use try with resources statements. See https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html. It basically will handle automatically closing closable objects for you.

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