Does a Java ByteArrayInputStream built off of bytes from a local String variable need to be closed?

1.1k views Asked by At

Let's say that I am constructing a Java ByteArrayInputStream off of a local String variable. For example, let's say that I have a large String named csv representing the contents of a CSV file and I need to put it into an input stream in order to have a component of my program read from that string, as opposed to from a file. For example,

InputStream inputStream = new ByteArrayInputStream(csv.​getBytes(StandardCharsets.UTF_8));

Does this inputStream need to be closed once I am done processing with it? I am aware that it is usually a good practice to close unused input streams, often via the try-resources construct. What I am specifically interested in right now is what would be the consequences of choosing not to close this input stream before this variable goes out of scope when its method returns. Would there be a memory leak because I left a stream open? Or would it not matter because the stream was open on a local variable instead of on a File resource?

2

There are 2 answers

0
Elliott Frisch On BEST ANSWER

No. You do not need to close a ByteArrayInputStream. Because it is in memory, there would be no consequences (it would be garbage collected). Now, if the InputStream was associated with an external resource (like a File) that could cause you to run out of file handles.

The ByteArrayInputStream Javadoc says (in part),

Closing a ByteArrayOutputStream has no effect.

0
fge On

I am aware that it is usually a good practice to close [...]

Then Just Do It (tm) :)

what would be the consequences of choosing not to close this input stream before this variable goes out of scope when its method returns[?]

In the case of a ByteArrayInputStream, no consequence; for some other InputStream implementations, leaks, leaks and more leaks.

Long story short: always .close() safely, you never lose; either using a try-with-resources statement in Java 7+, or for earlier versions, ideally using Guava's Closer.