//将图片缓存到内存中
public void put(String url, Bitmap bmp){
FileOutputStream fileOutputStream = null;
try{
fileOutputStream = new FileOutputStream(cacheDir + url);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
}catch (FileNotFoundException e){
e.printStackTrace();
}finally {
if(fileOutputStream != null){
try{
fileOutputStream.close();
}catch (IOException e){
e.printStackTrace();
}
}//end if
}// end if finally
}
public final class CloseUtils {
private CloseUtils(){}
/*
* 关闭Closeable对象
* @param closeable
* */
public static void closeQuietly(Closeable closeable){
if(null != closeable){
try {
closeable.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}
运用到put方法代码如下:
//将图片缓存到内存中
public void put(String url, Bitmap bmp){
FileOutputStream fileOutputStream = null;
try{
fileOutputStream = new FileOutputStream(cacheDir + url);
bmp.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
}catch (FileNotFoundException e){
e.printStackTrace();
}finally {
CloseUtils.closeQuietly(fileOutputStream);
}
}
该closeQuietly方法可以运用到各类可关闭的对象中,保证了代码的重用性,该方法的基本原理就是依赖于Closeable抽象而不是具体实现(依赖倒置原则),并且建立在最小化依赖原则的基础上,它只需要知道这个函数是可关闭的,其他的一概不关心,也就是这里的接口隔离原则。