Search code examples
javaexceptiontry-catchtry-with-resources

Multiple resources in Try-With-Resources - statments inside


I'm trying to specify multiple resources in a single Try-With-Resources statement but my situation is a bit different from the ones I read on other posts.

I've just tried the following Try-With-Resources

public static String myPublicStaticMethod(BufferedImage bufferedImage, String fileName) {

try (ByteArrayOutputStream os = new ByteArrayOutputStream();
    ImageIO.write(bufferedImage, "png", os);
    InputStream is = new ByteArrayInputStream(os.toByteArray());
    ) {
    .....
    .....
    }

But my code is not able to compile with this error:

Resource references are not supported at language level '8'

So, as you can see, my aim is to declare ByteArrayOutputStream os and InputStream is as resources of Try-With-Resources both but I have to call ImageIO.write() method before creating the InputStream.

Must I to use the usual try-catch-finally to close the streams?


Solution

  • You can only declare objects implementing AutoCloseable interface inside the try-with-resources block, so your ImageIO.write(bufferedImage, "png", os); statement is invalid there.

    As a workaround you can split this code into two try-catch-blocks, i.e.:

    try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
        ImageIO.write(bufferedImage, "png", os);
        try(InputStream is = new ByteArrayInputStream(os.toByteArray())) {
            //...
        }
    }