This method may fail to clean up (close, dispose of) a stream, database object, or other resource requiring an explicit cleanup operation. In general, if a method opens a stream or other resource, the method should use a try/finally block to ensure that the stream or resource is cleaned up before the method returns.

This is the code:

public void setSource(File file) throws IOException {

 m_structure = null;
 setRetrieval(NONE);

 if (file == null) {
  throw new IOException("Source file object is null!");
 }

 try {
  setSource(new FileInputStream(file));
 } 
 catch (FileNotFoundException ex) {
  throw new IOException("File not found");
 }
 
 m_File = file.getAbsolutePath();
}
1

There are 1 best solutions below

0
On

You get the error because of the following line:

new FileInputStream(file)

You could theoretically close the inputstream inside the setSource(InputStream is) method however that is not the correct scope. The convention is to close a stream where you opened it. So if you change your code to the following it should remove the warning. Please note that your catch block doesn't make sense since the FileNotFoundException is already an IOException. There are two possibilities:

  1. Try with resources:

    public void setSource(File file) throws YourOwnApplicationException{
    
     if (file == null) {
      throw new YourOwnApplicationException("Source file object is null!");
     }
    
     try (FileInputStream fis=new FileInputStream(file)){
      setSource(fis);
     } 
     catch (IOException | FileNotFoundException ex) {
      throw new YourOwnApplicationException("File not found");
     }
    }
    
  2. The pre Java 7/8 way:

    public void setSource(File file) throws YourOwnApplicationException {
    
     if (file == null) {
      throw new YourOwnApplicationException ("Source file object is null!");
     }
    
     FileInputStream fis=null;
     try {
         fis = new FileInputStream(file);
         setSource(fis);
     } 
     catch (IOException | FileNotFoundException ex) {
      throw new YourOwnApplicationException("File not found");
     }
     finally {
         if(fis!=null) {
             try {
                 fis.close();
             }
             catch(IOException ioe) {
                 //swallow
             }
         }
     }
    }
    

If you do it like this it also means that you have to consume your InputStream inside the setSource(InputStream is) method. Otherwise it wouldn't make sense to close it...