从服务器上请求的数据,对于一些不是经常变化的数据,可以存储到本地。从而可以实现在无网络或者
网络状态不好的情况实现数据的获取,界面的正常展示,同时也可以减少用户流量消耗,也可减轻服务
器的压力。该工具类,主要封装了对字符串数据的存储,以及图片的存储。目前可以满足我所做项目的
需求,若有不合理的地方,希望各位大神能不啬赐教!
代码实现:
public class FileUtils {
//设置文件的超时时间
public static int CACHE_TIME = 3 * 60 * 1000;
/*
* 字符串保存到本地
* 返回值:字符串写入本地是否成功
* 思路:若文件存在,则删除;然后创建一个新的文件,并把数据写入文件
* */
public static boolean write2File(Context context, String str, String fileName) {
boolean result = false;
try {
if (StringUtils.isEmpty(fileName)) {
return result;
}
deleteFile(context,fileName);
File file = new File(context.getFilesDir(), fileName);
file.createNewFile();
FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(str.getBytes());
fos.close();
result = true;
} catch (Exception e) {
e.printStackTrace();
result = false;
}
return result;
}