Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

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:

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top