乐趣区

Java关于IO的一个小工具

考虑这样一种场景,你要为系统编写一个下载文件并缓存到本地的功能,你会用到 InputSteam 和 OutputStream 类,你可能会这么写:
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(“”);
os = new FileOutputStream(“”);
// 下载文件的代码
// 保存到本地的代码
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
在 finally 代码块中,为了关闭两个 IO 流居然写了 14 行代码,假如每次用到 IO 的时候都写一大堆 if……else,也挺烦的,有没有什么办法可以用一行代码就搞定呢?查看 InputStream 和 OutputStream 抽象类源代码,发现他们都实现了共同的接口 Closeable,事实上,java 中所有 Stream 类都必须实现这个接口,那么,这下就好办了。我们可以设计一个工具类,如下:
public class IOUtil {
public static void close(Closeable… closeableList) {
try {
for (Closeable closeable : closeableList) {
if (closeable != null){
closeable.close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
那么,在 finally 代码块中就可以这样写:
finally{
/* 这些代码都可以省略
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
*/
// 只需要下面这一行代码就可以了
IOUtil.close(is, os);
}
是不是方便了很多呢?这个工具类用到了可变参数,接口隔离的思想。这样写代码,不仅仅只是方便而已,代码的可读性也好了很多,不是吗?

退出移动版