Utility class used to deal with SD card cache. : Environment « Core Class « Android






Utility class used to deal with SD card cache.

    
package net.javalib.flickr.search.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

/**
 * Utility class used to deal with SD card cache.
 */
public class CacheUtil {
  /** Cache root */
  private static File root;
  
  private CacheUtil() {}
  
  static {
    root = Environment.getExternalStorageDirectory();
    root = new File(root,"FlickrSearch/cache");
  }
  
  public static File file(String cacheKey) {
    return new File(root,cacheKey);
  }
  
  public static void deleteCache() {
    deleteDir(root);
  }
  
  public static void deleteDir(File dir) {
    if (!dir.isDirectory())
      return;
    File[] files = dir.listFiles();
    for (File file : files) {
      if (file.isDirectory())
        deleteDir(file);
      else {
        file.delete();
      }
    }
  }
  
  public static boolean exists(String cacheKey) {
    return file(cacheKey).exists();
  }
  
  public static Bitmap getBitmap(String cacheKey) {
    if (!exists(cacheKey))
      return null;
    File file = file(cacheKey);
    InputStream in = null;
    try {
      in = new FileInputStream(file);
      return BitmapFactory.decodeStream(in);
    } catch (Exception e) {
      return null;
    } finally {
      if (in != null) try { in.close(); } catch (Exception e) {}
    }
  }
  
}

   
    
    
    
  








Related examples in the same category

1.Create a new directory on external storage
2.May crash when External-Media is not mounted.
3.is Storage Readable/Writable
4.Get External Storage Directory
5.Environment.MEDIA_MOUNTED, Environment.MEDIA_MOUNTED_READ_ONLY
6.return True if the external storage is available/writable.