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

/**
 * 方法名: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();
}

//------------------------------------------------------------------------完----------------------------------------------------------------------------------- 

你可能感兴趣的:(android)