use*_*115 0 java exception inputstream outputstream ioexception
我试图将输入流图像写入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);
}
Run Code Online (Sandbox Code Playgroud)
readImage:
public static InputStream readImage(String file) throws IOException {
try (InputStream input = new FileInputStream(file)) {
return input;
}
}
Run Code Online (Sandbox Code Playgroud)
但写作时我收到错误:
java.io.IOException: Stream Closed
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
退出块时,try-with-resources会关闭流
try (InputStream input = new FileInputStream(file)) {
Run Code Online (Sandbox Code Playgroud)
即.当你的方法返回时.
只需删除它,并在其他方法体的末尾处理关闭流.
正如评论中所述,这里是官方教程的链接try-with-resources.
| 归档时间: |
|
| 查看次数: |
1304 次 |
| 最近记录: |