Search code examples
javasonarqubefileinputstreamautocloseable

Java- How can you close `FileInputStream` in finally block if the same method returns that `FileInputStream`


Sonar is showing a bug for the below code which is of blocker type. It's complaining that I have not closed FileInputStream but how can I do that? FileInputStream is the return type of method and if I close here then it will be of no use from where it's calling. Please let me know- how can I close FileInputStream in finally block if the same method returns that FileInputStream?

Here is the code:

@Override
public InputStream getInputStream() throws MissingObjectException {

    try {
        InputStream is;
        if (smbFile != null) {
            is = new BufferedInputStream(new SmbFileInputStream(smbFile), 60000);
        } 
        else {
            is = new BufferedInputStream(new FileInputStream(getFilePath()));
        }
        return is;
    }
    catch (Exception e) {
            throw new MissingObjectException();
    }
}

Solution

  • It is not necessary to close the input in the same function. The problem may be that you should not declare InputStream is in try{} block as well as putting the return statement.