您的位置:首页 > 其它

第一个封装工具:可以运用于各类可关闭的对象中

2016-07-16 19:33 323 查看
这个是从 《android源码设计解析与实战上看的》

可以运用于各类可关闭的对象。 p16

![这里写图片描述](http://img.blog.csdn.net/20160716193144169)
package com.oldeleven.day16_internalstoragefiles.utils;

import java.io.Closeable;
import java.io.IOException;

/**
* Created by My on 2016/7/16.
*/
public final class CloseUtils {
private CloseUtils(){}
public static void closeQuietly(Closeable closeable){
if (null != closeable){
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}


实例:

代码片段:

case R.id.button_main_restore:
//取数据并显示到textView_main_result
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
bis = new BufferedInputStream(openFileInput(FILE_NAME));
baos = new ByteArrayOutputStream();
byte[] data = new byte[1024*3];
int len = 0;
while ((len = bis.read(data)) != -1){
baos.write(data,0,len);
baos.flush();
}
textView_main_result.setText(baos.toString());
} catch (IOException e) {
e.printStackTrace();
}finally {
CloseUtils.closeQuietly(bis);
CloseUtils.closeQuietly(baos);
}
break;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: