【问题标题】:Closing the stream only if it's opened仅在打开时关闭流
【发布时间】:2012-03-31 14:24:54
【问题描述】:

考虑这段代码:

    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 objectoutputstream


    【解决方案1】:

    如果您使用的是 Java 7,则可以使用 try-with-resources 语句为您处理所有关闭操作。

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

    【讨论】:

    • 我在哪里关闭流?
    • @Ramy AI Zuhouri try-with-resources 语句会在块退出时为您关闭流。阅读我给你的链接。
    【解决方案2】:

    在你的 try-catch 语句中添加一个 finally 块并在那里进行关闭。为避免再次出现 try-catch 和 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);
        }      
    

    【讨论】:

      【解决方案3】:

      您可以在关闭流之前添加一个 if 条件,如下所示

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-07-27
        • 2020-05-16
        • 2012-11-26
        • 1970-01-01
        • 1970-01-01
        • 2019-06-26
        • 2013-07-09
        • 2011-04-16
        相关资源
        最近更新 更多