做项目的时候,经常会需要本地保存一些对象,如果用数据库去保存吧,会显得大材小用;比如保存用户的登陆信息,一些页面的初始化数据,用于离线显示等等...接口返回给你一大串js格式的字符串,通常大家都会去建个模型区解析成一个类的对象,那么我们该如何高效的保存这些对象呢。
这里java给出了两个类ObjectOutputStream和ObjectInputStream,一个用于写入对象到指定文件路径,一个用于读取指定文件路径,并解析成相应的对象。
不墨迹,直接上自己封装的类:
package com.sitsmice.idevevt_jar.utils; import com.sitsmice.idevevt_jar.MLog; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * Created by sahara on 2016/4/12. */ public class UtilObjectIO { /** * 根据类名读取相应的缓存文件, * @param clss * @param strs(可变参数,字符串数组) * @param <T> * @return */ public static <T> T readObject(Class<T> clss,String path ,String... strs){ String str = ""; for (String s:strs) { str = str+"/"+s; path = path+"/"+s; UtilFile.isHaveFile(path); } File file = new File(path+"/"+clss.getSimpleName()+".txt"); T t = null; try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file)); try { t = (T) ois.readObject(); MLog.e("test","UtilObjectIO:读取"+str+"/"+clss.getSimpleName()+"成功!"); ois.close(); } catch (ClassNotFoundException e) { MLog.e("test","UtilObjectIO error:"+str+"没有读到缓存文件"+e.getMessage()); e.printStackTrace(); } } catch (IOException e) { MLog.e("test","UtilObjectIO error:读取异常"+e.getMessage()); e.printStackTrace(); } return t; } /** * 将泛型参数对象写成文件,用于存储 * @param t * @param strs(可变参数,字符串数组) * @param <T> */ public static <T> void writeObject(T t,String path,String... strs){ String str = ""; for (String s:strs) { str = str + "/" + s; path = path+"/"+s; UtilFile.isHaveFile(path); } File file = new File(path+"/"+t.getClass().getSimpleName()+".txt"); try { ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file)); oos.writeObject(t); oos.close(); MLog.e("test", "UtilObjectIO:写入" + str +"/"+ t.getClass().getSimpleName() + "成功!"); } catch (IOException e) { MLog.e("test","UtilObjectIO error:写入异常"+e.getMessage()); e.printStackTrace(); } } }
/** * path为文件夹 保证存在 * path为文件 保证父文件夹存在 * @param path * @return: boolean 是否存在此文件(如里是文件夹则为true) */ public static boolean isHaveFile(String path) { MLog.i("test","检查文件路径是否存在"); if (path == null) { return false; } File file = new File(path); if (file.isFile()) {// 是文件 if (file.exists()) { return true;// 存在此文件 } File parentFile = file.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } return false; } else {// 是文件夹 if (!file.exists()) { MLog.e("test","生成文件路径:"+path); file.mkdirs(); } return true; } }
使用起来非常easy,我定义的都是静态方法直接拿类名去调就可以了,注释写的很清楚,有什么疑问欢迎留言。