0

I'am trying to write the inputstream image to OutputStream to display the image in the browser this is the code:

try
{
    InputStream input = Filer.readImage("images/test.jpg");
    byte[] buffer = new byte[1024];
    int bytesRead;
    while ((bytesRead = input.read(buffer)) != -1)
    {
        responseBody.write(buffer, 0, bytesRead);
    }
}
catch(IOException e)
{
    System.out.println(e);
}

the readImage:

public static InputStream readImage(String file) throws IOException {
    try (InputStream input = new FileInputStream(file)) {

        return input;
    }
}

but I get an error while writing:

java.io.IOException: Stream Closed

any ideas?

2 Answers 2

5

The try-with-resources closes the stream when you exit the block

try (InputStream input = new FileInputStream(file)) {

ie. when your method returns.

Just remove it and take care of closing the stream at the end of your other method body.

As stated in the comments, here's a link to the official tutorial on try-with-resources.

Sign up to request clarification or add additional context in comments.

1 Comment

The link to the doc would be nice to have in your answer.
1

Taken from oracle tutorial the resource is closed when the statement completes:

The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.