Should a Java ByteArrayInputStream built from bytes from a local String variable be closed?

Let's say that I am building Java ByteArrayInputStream

with a String local variable. For example, let's say that I have a large Named String csv

representing the content of a CSV file and I need to put it on an input stream in order to have a component of my program read from that string as opposed to a file. For example,

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

      

Do I need to close this input stream after I have finished processing it? I know it is generally a good idea to close unused input streams, often through the try-resources construct. What I'm particularly interested in right now is what would be the consequences of not choosing to close this input stream before this variable goes out of scope when its method returns. Will there be a memory leak because I left the stream open? Or does it not matter because the stream was opened on a local variable and not on a file share?

+3


source to share


2 answers


Not. You don't need to close ByteArrayInputStream

. Since it is in memory, there will be no consequences (it will be garbage collection). Now if InputStream

was linked to an external resource (for example File

), that could cause you to end up working with files.

ByteArrayInputStream

The Javadoc
says (in part),



Closing a ByteArrayOutputStream

has no effect.

+4


source


I know it is usually recommended to close [...]

Then just do this (tm) :)

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



In case a, ByteArrayInputStream

there are no consequences; for some other implementations InputStream

, leaks, leaks and other leaks.

In short: it's always .close()

safe, you never lose; either using the try-with-resources statement in Java 7+, or for earlier versions, ideally using GuavaCloser

.

+1


source







All Articles