Skip to content

Instantly share code, notes, and snippets.

@extralam
Created June 28, 2013 02:39
Show Gist options
  • Save extralam/5882074 to your computer and use it in GitHub Desktop.
Save extralam/5882074 to your computer and use it in GitHub Desktop.
SimpleCacheStorage - Simple File Cache System
package com.kirin.util;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.content.Context;
/**
* Simple Cache System
* @author 阿目
*
*/
public class SimpleCacheStorage {
private static final String TAG = "SimpleCacheStorage";
private static final String PREFIX = "_CACHED_";
/**
*
* @param context
* @param key
* @param data
* @return success Saving or not
*/
public static boolean pull(Context context , String key , String data){
FileOutputStream fos = null;
try {
fos = context.openFileOutput( PREFIX + md5(key), Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.flush();
fos.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
*
* @param context
* @param key
* @return Cached Data
*/
public static String get(Context context , String key){
String datax = "";
try {
FileInputStream fIn = context.openFileInput ( PREFIX + md5(key) ) ;
InputStreamReader isr = new InputStreamReader ( fIn ) ;
BufferedReader buffreader = new BufferedReader ( isr ) ;
String readString = buffreader.readLine () ;
while ( readString != null ) {
datax = datax + readString ;
readString = buffreader.readLine () ;
}
isr.close () ;
} catch ( IOException ioe ) {
ioe.printStackTrace () ;
return null;
}
return datax ;
}
/**
* Local use for hash the key word
* @param s
* @return
*/
private static String md5(String s) {
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(s.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
for (int i=0; i<messageDigest.length; i++)
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment