Search code examples
javainputstreambytearrayinputstream

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


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?


Solution

  • 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.