java - Try-With-Resources 中的多个资源 - 里面的语句

标签 java exception try-catch try-with-resources

我试图在单个 Try-With-Resources 语句中指定多个资源,但我的情况与我在其他帖子中读到的情况有点不同。

我刚刚尝试了以下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());
    ) {
    .....
    .....
    }

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

Resource references are not supported at language level '8'

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

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

最佳答案

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

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

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

关于java - Try-With-Resources 中的多个资源 - 里面的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56968908/

相关文章:

c# - nUnit Assert.That(method,Throws.Exception) 不捕获异常

java - 无法捕获 EJB 中的异常

java不会解析为变量

java - 函数嵌套

java - hibernate 保存或更新行为

android - 从一个 Activity 开始另一个 Activity 时出现空指针异常

java - 不允许异常链接的 JDK 异常怎么了?

ios - 为什么Objective-C中的 "try catch"会导致内存泄漏?

java - 自定义异常仅在 try/catch block 中调用时打印出 null

java - 无法在我的 Future 参数上使用 get 方法来获取具有可调用接口(interface)的线程的结果