覆盖JSON对象而不完全替换文件Android Studio

qyzbxkaa  于 2023-06-24  发布在  Android
关注(0)|答案(2)|浏览(106)

基本上,我尝试覆盖以下JSON数据

{
    "name" : "John Doe",
    "gender" : "male",
    "age" : "21"
}

我的目标是只取代年龄。所以我像下面这样使用FileOutputStream

JSONObject object = new JSONObject();
try {
    object.put("age", "40");

} catch (JSONException e) {
    //do smthng
}

String textToSave = object.toString();

try {
    FileOutputStream fileOutputStream = openFileOutput("credentials.txt", MODE_PRIVATE);
    fileOutputStream.write(textToSave.getBytes());
    fileOutputStream.close();
    intentActivity(MainMenu.class);

} catch (FileNotFoundException e) {
    //do smthng
} catch (IOException e) {
    //do smhtng
}

但是使用上面的代码,我意识到它完全删除了现有的credentials.txt,这意味着我丢失了namegender值。是否有任何方法可以取代age?谢谢你

sauutmhj

sauutmhj1#

基本上你的问题的答案是否定的。你的行动方针是
1.将文件读入存储器,
1.修改内存中的内容
1.用修改的内容覆盖旧文件。
下面是关于如何修改文本文件的问题,并给出了很好的答案:Modifying existing file content in Java

56lgkhnf

56lgkhnf2#

我已经找到答案了。基本上我需要读取现有的JSON文件,然后替换现有的JSON对象值

private void writeFile(String age) {
    try {
        FileInputStream fileInputStream = openFileInput("credentials.json");
        InputStreamReader isr = new InputStreamReader(fileInputStream);
        BufferedReader br = new BufferedReader(isr);

        StringBuilder jsonStringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            jsonStringBuilder.append(line);
        }
        br.close();

        String jsonString = jsonStringBuilder.toString();
        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObject = jsonParser.parse(jsonString).getAsJsonObject();

        jsonObject.addProperty("age", age);

        FileOutputStream fileOutputStream = openFileOutput("credentials.json", MODE_PRIVATE);
        OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream);
        BufferedWriter bw = new BufferedWriter(osw);

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String updatedJsonString = gson.toJson(jsonObject);

        bw.write(updatedJsonString);
        bw.flush();
        bw.close();

    } catch (FileNotFoundException e) {
        intentActivity(Login.class);
    } catch (IOException e) {
        intentActivity(Login.class);
    }
}

相关问题