1、添加Gson 库
右键app---open module settings----dependncies---com.goolel.code.gson:gson:2.2.4
2、对象转Json 保存至文件:
//使用Misc中的方法
Misc
.gson(
sConfig,
FG8KWApplication.getAppFilePath() + CONFIG_FILE_NAME);
MiseUtile
/**
* 保存 JSON对象至文件
*
* @param object 对象
* @param filename 文件名称
*
* @return
*/
public static boolean gson(Object object, String filename)
{
byte[] data = gson(object);
return FileUtils.saveBytesToFile(filename, data);
}
/**
* JSON 化对象
*
* @param object 对象
*/
public static byte[] gson(Object object)
{
Gson gson = new Gson();
String data = gson.toJson(object);
byte[] bytes = data.getBytes();
return bytes;
}
3、从文件中读取Json数据 成对象
String data = Misc.degson(FG8KWApplication.getAppFilePath() + CONFIG_FILE_NAME);
Gson gson = new Gson();
Config obj = gson.fromJson(data, Config.class);
/** * 从文件读取 JSON数据 * @param filename 文件名称 * @return */ public static String degson(String filename) { byte[] bytes = FileUtils.getBytesFromFile(filename); String data = new String(bytes); return data; }
4、存储数据至文件/从文件中读取数据/** * 将数据存储至文件中 * * @param filename 文件名 * @param data 文件内容 * * @return 是否成功, 成功返回errno.S_OK */ public static boolean saveBytesToFile(String filename, byte[] data) { try { DataOutputStream d = new DataOutputStream(new FileOutputStream( filename)); d.write(data); d.flush(); d.close(); return true; } catch (Exception e) { Tracker.e(e); return false; } } /** * 读取文件 * * @param filename 文件名 * * @return 文件内容 */ public static byte[] getBytesFromFile(String filename) { InputStream is = null; try { File file = new File(filename); is = new FileInputStream(file); // 获得文件尺寸 long length = file.length(); if (length > Integer.MAX_VALUE) { return null; } // 创建字节数组保存数据 byte[] bytes = new byte[(int) length]; // 读取字节 int offset = 0; int numRead = 0; while ((offset < bytes.length) && (numRead = is.read( bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } // 确保所有字节被读取 if (offset < bytes.length) { return null; } else { return bytes; } } catch (Exception e) { Tracker.e(e); return null; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } }