Nishant Lakhara
Nishant Lakhara

Reputation: 2455

Does InputSream needs to be closed if stream is made up using some String or byte array object in Java?

I have a small piece of code. I am creating an InputStream using the byte array and putting some data on server.

public void putStreamGetBytes() {
        try {
            String key = getKey();

            byte[] data = getTestData(getPayloadSize());
            InputStream stream = new ByteArrayInputStream(data);

            putStream(assetNWK, key, stream, true, RESPONSE_OK, VERSION_1_1, null, true);
            validateBytes(assetNWK, key, data, RESPONSE_OK, VERSION_1_1, null, true);
        } catch (Exception e) {
            handleError(e);
        }
    }

I haven't opened any resource like a file or something. Do I need to close the stream to avoid memory leaks?

Upvotes: 0

Views: 50

Answers (3)

Deepu--Java
Deepu--Java

Reputation: 3840

Sometimes you are not getting the expected output from your stream. So sometimes stream get block. To avoid these blockage you need to flush() the stream then close() it.

Here you are not using file or socket so memory leak would not happen but it's good practice to close stream after use.

Upvotes: 1

user2504380
user2504380

Reputation: 545

The only thing you are allocating for is the InputStream itself. Especially in cases of IOExceptions, depending on your usage of the code, this might be problematic anyway, i would suggest to use the try-with-resources syntax, if possible, like:

try(InputStream stream = new ByteArrayInputStream(data)){
......
}

Upvotes: 0

user3781876
user3781876

Reputation: 55

To avoid memory leakage. you need to free the stream. to free the stream you need to call the close method in final block.

Upvotes: 0

Related Questions