当前位置: 代码迷 >> 综合 >> 103.android 简单的保存、读取本地json文件
  详细解决方案

103.android 简单的保存、读取本地json文件

热度:77   发布时间:2024-01-24 05:26:34.0
/*** 方法名:saveToLocal()* 功    能:创建隐藏文件夹,保存json到本地* 参    数:无* 返回值:String*/
public static String saveToLocal() {//文件夹路径File dir = new File(Environment.getExternalStorageDirectory() + "/.TQRecorderConfig/jsonConfig/");//文件名String fileName = "config.json";try {//文件夹不存在和传入的value值为1时,才允许进入创建if (!dir.exists()) {//创建文件夹dir.mkdirs();JsonObject jsonObject = new JsonObject();jsonObject.addProperty("id", 0);jsonObject.addProperty("name", "apkName");jsonObject.addProperty("value", 0);String json = jsonObject.toString();File file = new File(dir, fileName);OutputStream out = new FileOutputStream(file);out.write(json.getBytes());out.close();XLog.i("RecordApp", "保存Config成功 path:" + file.getPath());return file.getPath();} else {XLog.i("RecordApp", "Config已经存在 path:" + dir + "/" + fileName);return dir + "/" + fileName;}} catch (Exception e) {e.printStackTrace();XLog.i("RecordApp", "Config保存失败");}return "";
}/*** 方法名:readJsonFile(String filePath)* 功    能:从本地读取json* 参    数:String filePath* 返回值:String*/
public static String readJsonFile(String filePath) {StringBuilder sb = new StringBuilder();try {File file = new File(filePath);InputStream in = null;in = new FileInputStream(file);int tempbyte;while ((tempbyte = in.read()) != -1) {sb.append((char) tempbyte);}in.close();} catch (Exception e) {e.printStackTrace();}return sb.toString();
}