-1

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();
    }
}
progyammer
  • 1,498
  • 3
  • 17
  • 29
Ashish Pancholi
  • 4,569
  • 13
  • 50
  • 88

2 Answers2

2

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.

Wojtek
  • 1,288
  • 11
  • 16
0

Put is declaration before try block

 InputStream is= null;
try {
    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();
}finally{
  if(is !=null){
  is.close();
 }
}
andolsi zied
  • 3,553
  • 2
  • 32
  • 43