簡體   English   中英

僅在流打開時關閉它

[英]Closing the stream only if it's opened

考慮以下代碼:

    FileOutputStream stream=null;
    ObjectOutputStream objStr=null;
    try
    {
        stream=new FileOutputStream(defaultFile);
        objStr=new ObjectOutputStream(stream);
        objStr.writeObject(obj);
        objStr.close();
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Il file "+ defaultFile+ " non è stato trovato\n");
    }
    catch(IOException e)
    {
        stream.close();
        System.out.println("Si è verificato un problema di I/O nell' apertura dello  stream");
    }

在第二個catch塊中,我關閉了流,但是不確定是否應該將其關閉。
如果ObjectOutputStream的構造函數失敗,它將進入第二個捕獲,但是我確定在這種情況下FileOutputStream保持打開狀態嗎?
我應該寫一個finally塊來處理所有異常嗎?
我很難弄清所有情況。

如果您使用的是Java 7,則可以使用try-with-resources語句為您處理所有結帳。

try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(defaultFile))) {
    oos.writeObject(obj);
} catch (IOException e) {
    e.printStackTrace();
}

在您的try-catch語句中添加一個finally塊,然后在此結束。 為了避免在那里再次嘗試捕獲和進行nullcheck,可以使用commons.io IOUtils.closeQuietly()

    FileOutputStream stream = null;
    ObjectOutputStream objStr = null;
    try {
        stream = new FileOutputStream(defaultFile);
        objStr = new ObjectOutputStream(stream);
        objStr.writeObject(obj);
    } catch (FileNotFoundException e) {
        System.out.println("Il file " + defaultFile + " non è stato trovato\n");
    } catch (IOException e) {
        System.out.println("Si è verificato un problema di I/O nell' apertura dello  stream");
    } finally {
        IOUtils.closeQuietly(stream);
        IOUtils.closeQuietly(objStr);
    }      

您可以在關閉流之前添加if條件,如下所示

if(stream != null) {
    stream.close();
}

暫無
暫無

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

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