栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

我是否必须关闭由PrintStream包装的FileOutputStream?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

我是否必须关闭由PrintStream包装的FileOutputStream?

不,您只需要关闭最外面的流。它将一直委托给包装的流。

但是,您的代码包含一个概念上的失败,应该在中发生关闭

finally
,否则当代码在打开和关闭之间引发异常时,它永远不会关闭。

例如

public static void main(String args[]) throws IOException {     PrintStream ps = null;    try {        ps = new PrintStream(new FileOutputStream("myfile.txt"));        ps.println("This data is written to a file:");        System.out.println("Write successfully");    } catch (IOException e) {        System.err.println("Error in writing to file");        throw e;    } finally {        if (ps != null) ps.close();    }}

(请注意,我更改了代码以 引发 异常,以便您了解问题的原因,该异常即包含有关问题原因的详细信息)

或者,当您已经在使用Java 7时,也可以使用ARM(自动资源管理;也称为try-with-
resources
),这样您就不需要自己关闭任何东西:

public static void main(String args[]) throws IOException {     try (PrintStream ps = new PrintStream(new FileOutputStream("myfile.txt"))) {        ps.println("This data is written to a file:");        System.out.println("Write successfully");    } catch (IOException e) {        System.err.println("Error in writing to file");        throw e;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495035.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号