harry-potter
harry-potter

Reputation: 2059

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?

Upvotes: 2

Views: 4283

Answers (3)

Ori Marko
Ori Marko

Reputation: 58832

First, Make sure your IDE language level is Java 8

When you want to add extra lines of code which aren't creating autoclosable resource inside try with resources block then you can add specific method wrapping it, in your case:

private InputStream getInputStream() {
    ImageIO.write(bufferedImage, "png", os);
    return new ByteArrayInputStream(os.toByteArray());
}

And call it in try with resources:

try (ByteArrayOutputStream os = new ByteArrayOutputStream();
    InputStream is = getInputStream()) {

I assume (as in your code) the extra lines relevant to creating the resource, if not just open an inner try with resources with your second resource as @PavelSmirnov suggested

Upvotes: 0

Dragoslav Petrovic
Dragoslav Petrovic

Reputation: 118

Try something like this:

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

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

You just declare resources used in try declaration, do the operations inside try block. Ofc you will need catch block also. Finally is not needed, except you wanna catch exceptions during closing of resources (suppressed exceptions)

Upvotes: -1

Pavel Smirnov
Pavel Smirnov

Reputation: 4799

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())) {
        //...
    }
}

Upvotes: 4

Related Questions