簡體   English   中英

嘗試將輸入流復制到輸出流時出現Java IOException

[英]Java IOException while trying to copy inputstream to outputstream

我正在嘗試將輸入流圖像寫入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);
}

readImage:

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

        return input;
    }
}

但我在寫時遇到錯誤:

java.io.IOException: Stream Closed

有任何想法嗎?

退出代碼塊時,try-with-resources關閉流

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

即。 當您的方法返回時。

只需將其刪除,並注意在其他方法主體的末尾關閉流。

如評論中所述, 這是指向try-with-resources官方教程的鏈接

語句完成后,從oracle教程中獲取資源:

try-with-resources語句可確保在語句末尾關閉每個資源。 任何實現java.lang.AutoCloseable的對象(包括所有實現java.io.Closeable的對象)都可以用作資源。

在Java SE 7之前,您可以使用finally塊來確保關閉資源,而不管try語句是正常完成還是突然完成。 以下示例使用finally塊而不是try-with-resources語句:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM