//將圖片緩存到內存中
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抽象而不是具體實現(依賴倒置原則),並且建立在最小化依賴原則的基礎上,它只需要知道這個函數是可關閉的,其他的一概不關心,也就是這裏的接口隔離原則。