public class CacheUtils {
private static final String SP_NAME = "hefei_news";
public static void putBoolean(Context context, String key, Boolean value) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
sp.edit().putBoolean(key, value).commit();
}
/**
* 获取全局的Boolean类型值
* @param context
* @param key
* @return
*/
public static Boolean getBoolean(Context context,String key){
SharedPreferences sp=context.getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
return sp.getBoolean(key,false);
}
public static void putString(Context context,String key,String value){
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String fileName=null;
try {
fileName=MD5Encoder.encode(key);
File file=new File(Environment.getExternalStorageDirectory()+"/hefeinews",fileName);
File parentFile=file.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos=new FileOutputStream(file);
fos.write(value.getBytes());
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
SharedPreferences sp=context.getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
sp.edit().putString(key,value).commit();
}
}
/**
* 获取全局的String类型值
* @param context
* @param key
* @return
*/
public static String getString(Context context,String key){
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String fileName=null;
String result="";
try {
fileName=MD5Encoder.encode(key);
File file=new File(Environment.getExternalStorageDirectory()+"/hefeinews",fileName);
byte[] buffer=new byte[1024];
ByteArrayOutputStream stream=new ByteArrayOutputStream();
FileInputStream fis=new FileInputStream(file);
int len;
while ((len=fis.read(buffer))!=-1){
stream.write(buffer,0,len);
}
stream.close();
fis.close();
result=stream.toString();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}else{
SharedPreferences sp=context.getSharedPreferences(SP_NAME,Context.MODE_PRIVATE);
return sp.getString(key,"");
}
}
}
SharedPreferences 和本地文件缓存类
最新推荐文章于 2022-08-29 17:19:03 发布