内容简介:考虑这样一种场景,你要为系统编写一个下载文件并缓存到本地的功能,你会用到InputSteam和OutputStream类,你可能会这么写:在finally代码块中,为了关闭两个IO流居然写了14行代码,假如每次用到IO的时候都写一大堆if……else,也挺烦的,有没有什么办法可以用一行代码就搞定呢?查看InputStream和OutputStream抽象类源代码,发现他们都实现了共同的接口我们可以设计一个工具类,如下:
考虑这样一种场景,你要为系统编写一个下载文件并缓存到本地的功能,你会用到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);
}
是不是方便了很多呢?这个工具类用到了可变参数,接口隔离的思想。这样写代码,不仅仅只是方便而已,代码的可读性也好了很多,不是吗?
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:- ENVI扩展工具:RandomForest分类工具
- 15大安全工具和下载黑客工具
- 版本管理工具及 Ruby 工具链环境
- [译]Go性能分析工具工具和手段
- 工具 | 一个在线生成 nginx 配置文件的开源工具
- 【工具分享】PxCook像素大厨——很好用的标记工具
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Art of Computer Programming, Volumes 1-3 Boxed Set
Donald E. Knuth / Addison-Wesley Professional / 1998-10-15 / USD 199.99
This multivolume work is widely recognized as the definitive description of classical computer science. The first three volumes have for decades been an invaluable resource in programming theory and p......一起来看看 《The Art of Computer Programming, Volumes 1-3 Boxed Set》 这本书的介绍吧!