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

在Java中关闭嵌套流和编写器的正确方法

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

在Java中关闭嵌套流和编写器的正确方法

我通常会执行以下操作。首先,定义一个基于模板方法的类来处理try / catch混乱

import java.io.Closeable;import java.io.IOException;import java.util.linkedList;import java.util.List;public abstract class AutoFileCloser {    // the core action pre that the implementer wants to run    protected abstract void doWork() throws Throwable;    // track a list of closeable thingies to close when finished    private List<Closeable> closeables_ = new linkedList<Closeable>();    // give the implementer a way to track things to close    // assumes this is called in order for nested closeables,    // inner-most to outer-most    protected final <T extends Closeable> T autoClose(T closeable) { closeables_.add(0, closeable); return closeable;    }    public AutoFileCloser() {        // a variable to track a "meaningful" exception, in case        // a close() throws an exception        Throwable pending = null;        try { doWork(); // do the real work        } catch (Throwable throwable) { pending = throwable;        } finally { // close the watched streams for (Closeable closeable : closeables_) {     if (closeable != null) {         try {  closeable.close();         } catch (Throwable throwable) {  if (pending == null) {      pending = throwable;  }         }     } } // if we had a pending exception, rethrow it // this is necessary b/c the close can throw an // exception, which would remove the pending // status of any exception thrown in the try block if (pending != null) {     if (pending instanceof RuntimeException) {         throw (RuntimeException) pending;     } else {         throw new RuntimeException(pending);     } }        }    }}

请注意“待处理”异常-处理关闭期间抛出的异常会掩盖我们可能真正关心的异常的情况。

最后尝试首先从任何装饰的流的外部关闭,因此,如果你有包裹FileWriter的BufferedWriter,我们将尝试先关闭BuffereredWriter,如果失败,仍然尝试关闭FileWriter本身。(请注意,Closeable的定义要求close()在流已关闭的情况下忽略该调用)

你可以按如下方式使用上述类:

try {    // ...    new AutoFileCloser() {        @Override protected void doWork() throws Throwable { // declare variables for the readers and "watch" them FileReader fileReader =          autoClose(fileReader = new FileReader("somefile")); BufferedReader bufferedReader =          autoClose(bufferedReader = new BufferedReader(fileReader)); // ... do something with bufferedReader // if you need more than one reader or writer FileWriter fileWriter =          autoClose(fileWriter = new FileWriter("someOtherFile")); BufferedWriter bufferedWriter =          autoClose(bufferedWriter = new BufferedWriter(fileWriter)); // ... do something with bufferedWriter        }    };    // .. other logic, maybe more AutoFileClosers} catch (RuntimeException e) {    // report or log the exception}

使用这种方法,你不必担心尝试/捕获/最终再次处理关闭文件的麻烦。

如果这对于你的使用来说太重了,至少要考虑遵循try / catch及其使用的“ pending”变量方法。



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

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

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