在业务开发中经常会遇到需要保存对象到文件的需求,如下函数是通过FileChannel来保存ArrayList<HashMap<String, String>>对象到磁盘,并从磁盘读取还原ArrayList<HashMap<String, String>>对象的方法:
/**
* 保存加密后的数据到本地磁盘
* @param context 上下文
* @param data 需要保存的ArrayList<HashMap<String, String>>
* @param path 保存路径
* @return boolean
*/
public static synchronized boolean saveObject(Context context, ArrayList<HashMap<String, String>> data, String path) {
try {
byte[] encrypted = encryptData(DeviceHelper.getInstance(context).getModel(), data);
FileOutputStream fos = new FileOutputStream(path);
FileChannel channel = fos.getChannel();
channel.write(ByteBuffer.wrap(encrypted));
channel.force(true);//强制刷新
channel.close();
return true;
} catch (Throwable t) {
}
return false;
}
/**
* 从本地磁盘获取已保存的数据
* @param context 上下文
* @param path 路径
* @return ArrayList<HashMap<String, String>>
*/
public static synchronized ArrayList<HashMap<String, String>> loadObject(Context context, String path) {
try {
FileInputStream fis = new FileInputStream(path);
FileChannel channel = fis.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate((int) channel.size());
while ((channel.read(byteBuffer)) > 0) {
// do nothing
}
byte[] dataByte = byteBuffer.array();
channel.close();
return decryptData(DeviceHelper.getInstance(context).getModel(), dataByte);
} catch (Throwable t) {
}
return new ArrayList<HashMap<String, String>>();
}
private static byte[] encryptData(String key, ArrayList<HashMap<String, String>> data) {
Hashon hashon = new Hashon();
String json = hashon.fromObject(data);
try {
return Data.AES128Encode(key, json);
} catch (Throwable t) {
}
return json.getBytes();
}
private static ArrayList<HashMap<String, String>> decryptData(String key, byte[] dataByte) {
try {
String decrypted = Data.AES128Decode(key, dataByte);
ArrayList<HashMap<String, String>> list = getArrayListByString(decrypted);
return list;
} catch (Throwable t) {
}
return new ArrayList<HashMap<String, String>>();
}
private static ArrayList<HashMap<String, String>> getArrayListByString(String json) {
try {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
if (TextUtils.isEmpty(json)) {
return list;
}
JSONArray jsonArray = new JSONArray(json);
Hashon hashon = new Hashon();
for (int i = 0; i < jsonArray.length(); i++) {
list.add(hashon.<String>fromJson(jsonArray.getJSONObject(i).toString()));
}
return list;
} catch (Throwable t) {
}
return new ArrayList<HashMap<String, String>>();
}