FileUtils文件存储,实现文字和图片的本地存储

来源:互联网 发布:bitcomet mac版下载 编辑:程序博客网 时间:2024/06/08 14:13

从服务器上请求的数据,对于一些不是经常变化的数据,可以存储到本地。从而可以实现在无网络或者
网络状态不好的情况实现数据的获取,界面的正常展示,同时也可以减少用户流量消耗,也可减轻服务
器的压力。该工具类,主要封装了对字符串数据的存储,以及图片的存储。目前可以满足我所做项目的
需求,若有不合理的地方,希望各位大神能不啬赐教!

代码实现:

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;    }  /*   * 字符串以流的形式保存到本地   * 返回值:字符串写入本地是否成功   * 思路:若文件存在,则删除;然后创建一个新的文件,并把数据写入文件   * */    public static void write2File(Context context, InputStream in, String fileName) {        try {            deleteFile(context,fileName);            File file = new File(context.getFilesDir(), fileName);            file.createNewFile();            ByteArrayOutputStream bos = new ByteArrayOutputStream();            byte[] bytes = new byte[1024 * 4];            int n = 0;            while ((n = in.read(bytes)) != -1) {                bos.write(bytes, 0, n);            }            FileOutputStream fos = context.openFileOutput(filepath, Context.MODE_PRIVATE);            fos.write(bos.toByteArray());            fos.close();            bos.close();            in.close();            bytes = null;        } catch (IOException e) {            e.printStackTrace();        }    }    /*    * 从本地获取文件字符串    * boolean cacheTime:缓存时间是否有效。true(有效),文件存储时    * 间超时,则不取;false(无效),不论文件是否超时,都取。    * */    public static String read2File(Context context, String fileName,boolean cacheTime) {        String result = "";        try {            if (context == null || StringUtils.isEmpty(fileName)) {                return result;            }            File file = new File(context.getFilesDir(), fileName);            if (!file.exists()) {                return result;            } else if ( cacheTime && System.currentTimeMillis() - file.lastModified() > CACHE_TIME) {                return result;            }            FileInputStream fis = context.openFileInput(fileName);            byte[] bytes = new byte[fis.available()];            fis.read(bytes);            result = new String(bytes);            fis.close();            bytes = null;        } catch (Exception e) {            e.printStackTrace();        }        return result;    }    //通过文件名删除文件    public static boolean deleteFile(Context context, String fileName) {        boolean ret = false;        File file = new File(context.getFilesDir(), fileName);        if (file.exists()) {            file.delete();            ret = true;        }        return ret;    }    //把图片存入本地    public static boolean writeBitmap2File(Context context, Bitmap bitmap, String fileName) {        boolean result = false;        try {            deleteFile(context,fileName);            File file = new File(context.getFilesDir(), fileName);            file.createNewFile();            FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);            bitmap.compress(Bitmap.CompressFormat.PNG, 80, fos);            fos.flush();            fos.close();            result = true;        } catch (Exception e) {            e.printStackTrace();            result = false;        }        return result;    }    //从本地获取图片    public static Bitmap readBitmap2Cache(Context context, String fileName,boolean cacheTime) {        Bitmap bitmap = null;        try {            File file = new File(context.getFilesDir(), fileName);            if (!file.exists()) {                return bitmap;            } else if (cacheTime && System.currentTimeMillis() - file.lastModified() > CACHE_TIME_PIC) {                return bitmap;            }            FileInputStream fis = context.openFileInput(fileName);            BitmapFactory.Options options = new BitmapFactory.Options();            options.inPreferredConfig = Bitmap.Config.RGB_565;            options.inPurgeable = true;// 允许可清除            options.inInputShareable = true;// 以上options的两个属性必须联合使用才会有效果            bitmap = BitmapFactory.decodeStream(fis, null, options);            fis.close();        } catch (Exception e) {            e.printStackTrace();        }        return bitmap;    }    //根据id获取图片    public static Bitmap readBitMap(Context context, int resId) {        BitmapFactory.Options options = new BitmapFactory.Options();        options.inPreferredConfig = Bitmap.Config.RGB_565;        options.inPurgeable = true;        options.inInputShareable = true;        // 获取资源图片        InputStream is = context.getResources().openRawResource(resId);        return BitmapFactory.decodeStream(is, null, options);    }}   

数据获取策略描述:

数据获取策略

先从本地文件中获取数据,若文件不存在,或文件存储时间超时,则不取,否则直接取数据。若从本地
文件获取数据成功,则直接返回数据,若获取失败,则从网络获取数据。获取数据成功则直接返回数
据,并保存到本地文件中,若获取失败,则从本地文件中获取数据,不论文件是否超过存储时间,均从
本地获取数据,并返回。这样可以保证,只要数据曾经从网络上获取到过,以后正能获取到数据。从而
保证了数据曾经获取过,以后都能获取到数据!
不足之处,希望能够给予批评和指正!

0 0