code_buddy
code_buddy

Reputation: 75

How to fix 'Stream closed' error while using Streams in Java

Issue is: When I run sonar check(to analyse my code for bugs) on the below code, it complains the the FileInputStream in ClassA -> createFile() is not closed. I understand that this is a resource leak and needs to be closed. However, if I use try with resources or close the stream in finally block, ClassB complains that it could not read the stream as it was closed.

What is the best approach to solve this issue?

Code block:

public ClassA{
    public ClassB createFile(){
        return new ClassB(new FileInputStream(new File("filePath")), revision, .. other arguments);
    }
}

public ClassB{
    public ClassB(InputStream fileInputStream, String revision, other arguments){
        // save the arguments in class variables. Do something with stream
    }
}

Upvotes: 0

Views: 1257

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102795

For resources (things you need to close), you get three options:

1) You create it here, you close it here: Use the try-with-resources construct.

2) You pass the resource to an object, and then THAT object is itself a closable resource; when that resource is closed, it closes the resource inside it.

3) Weird stuff, not recommended, linters such as sonar will mark it as problematic, hard to debug, etc.

Naturally, you should avoid #3 as much as you can.

Here, it looks like you have 2 feasible options:

  1. Make ClassB implement AutoClosable and have it close that inputstream in its close method, or

  2. instead of passing an inputstream, pass a thingie from which an inputstream can be derived, so that the code of ClassB that uses it, can do the try-with-resources thing. Presumably, you'd pass perhaps a Path or File object instead of an InputStream.

Upvotes: 1

Related Questions