gpt4 book ai didi

尝试将输入流复制到输出流时发生 Java IOException

转载 作者:行者123 更新时间:2023-12-01 08:07:18 25 4
gpt4 key购买 nike

我正在尝试将输入流图像写入OutputStream以在浏览器中显示图像,这是代码:

try
{
InputStream input = Filer.readImage("images/test.jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buffer)) != -1)
{
responseBody.write(buffer, 0, bytesRead);
}
}
catch(IOException e)
{
System.out.println(e);
}

读取图像:

public static InputStream readImage(String file) throws IOException {
try (InputStream input = new FileInputStream(file)) {

return input;
}
}

但是我在编写时遇到错误:

java.io.IOException: Stream Closed

有什么想法吗?

最佳答案

退出 block 时,try-with-resources 会关闭流

try (InputStream input = new FileInputStream(file)) {

即。当你的方法返回时。

只需将其删除并在其他方法主体末尾关闭流即可。

正如评论中所述,here's a link to the official tutorial on try-with-resources .

关于尝试将输入流复制到输出流时发生 Java IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20641577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com