我试图在单个 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 os
和 InputStream 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/