关于java:Try-With-Resources中的多种资源-内部语句

Multiple resources in Try-With-Resources - statments inside

我正在尝试在单个Try-With-Resources语句中指定多个资源,但我的情况与我在其他文章中所读的内容有所不同。

我刚刚尝试了以下Try-With-Resources

1
2
3
4
5
6
7
8
9
public static String myPublicStaticMethod(BufferedImage bufferedImage, String fileName) {

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

但是我的代码无法编译并出现以下错误:

1
Resource references are not supported at language level '8'

因此,如您所见,我的目标是将ByteArrayOutputStream osInputStream is声明为Try-With-Resources的资源,但是在创建InputStream之前,我必须调用ImageIO.write()方法。

我是否必须使用通常的try-catch-finally来关闭流?


您只能在try-with-resources块内声明实现AutoCloseable接口的对象,因此您的ImageIO.write(bufferedImage,"png", os);语句在那里无效。

作为一种解决方法,您可以将此代码分为两个try-catch-blocks,即:

1
2
3
4
5
6
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
    ImageIO.write(bufferedImage,"png", os);
    try(InputStream is = new ByteArrayInputStream(os.toByteArray())) {
        //...
    }
}


尝试类似这样的内容:

1
2
3
4
5
6
7
public static String myPublicStaticMethod(BufferedImage bufferedImage, String fileName) {

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

您只需声明try声明中使用的资源,然后在try块内执行操作。 Ofc您还将需要catch块。最后是不需要的,除非您想在资源关闭期间捕获异常(抑制的异常)


首先,确保您的IDE语言级别为Java 8

如果要添加额外的代码行,而不是在try with resources块内创建无法自动关闭的资源,则可以添加package它的特定方法,以您的情况为例:

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

并尝试使用以下资源进行调用:

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

我假设(如您的代码中)与创建资源相关的额外行,如果不只是使用第二个资源(如@PavelSmirnov建议的那样)对资源进行内部尝试的话