这个是从 《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;
}