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();
}

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章