guava中Closer的用法
来源:互联网 发布:python实现搜索引擎 编辑:程序博客网 时间:2024/06/06 00:47
在JDK7以前,对文件操作,我们需要时刻注意用完后关闭文件。
InputStream in = null;
try {
in = openInputStream();
OutputStream out = null;
try {
out = openOutputStream();
// do something with in and out
} finally {
if (out != null) {
out.close();
}
}
} finally {
if (in != null) {
in.close();
}
}
可以看到,这段代码真是太复杂了,一不小心就出错了。
可喜的是JDK7有了新的措施来解决这类问题,那就是try-with-resources 语句,如:
try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
基本语法是:try(…) {} ,try里面所有实现接口java.lang.AutoCloseable,包括java.io.Closeable的对象,在{}的语句块执行完毕后都会自动的close。
那JDK7以前的版本怎么办呢,guava给我们提供了方法。我们可以把Closeable 的对象注册到Closer对象上,资源使用完毕后,调用closer的close方法,就可以把所有注册了的资源安全的close掉。这个方法虽然没有try-with-resources好用,但是比起传统的jdk做法,要好很多了。
Closer closer = Closer.create();
try {
InputStream in = closer.register(openInputStream());
OutputStream out = closer.register(openOutputStream());
// do stuff with in and out
} catch (Throwable e) { // must catch Throwable
throw closer.rethrow(e);
} finally {
closer.close();
}
- guava中Closer的用法
- Guava中Splitter和Joiner的用法
- 【Guava的用法】1. base
- 【Guava的用法】2. collection
- Google Guava的splitter用法
- guava中String的CharMatcher
- guava中String的CaseFormat
- Guava中Cache的使用
- Guava的Ordering的一个API用法
- Google Guava中Preconditions的用法,让前置条件判断变得更优雅
- Guava中EventBus的使用和详解
- google guava中定义的String操作
- Guava用法总结
- Guava基本用法
- Guava用法小计
- Guava中的Strings用法
- Guava Predicate 用法整理
- java,Iterator用法,Guava用法
- php,js部分语法 cookie session
- hdu 5138 CET-6 test(BestCoder Round #21)
- 专业在线教育平台大批量倒闭,在线教育有无前途
- css hack简介
- conversion to dalvik format failed with ...
- guava中Closer的用法
- Mariadb yum install repo
- shell中的basename dirname read
- daemon not running.starting it now on port 5037 *
- 数据结构_优先队列
- iOS_简单的数据存储
- eclipse快捷键及各种设置
- 【记录】C++中的static成员
- OC面向对象之继承