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

huangapple go评论65阅读模式
英文:

Overwrite JSON object without replacing the file completely Android Studio

问题

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

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

我的目标是只替换年龄。所以我使用FileOutputStream如下

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

} catch (JSONException e) {
    //做某事
}

String textToSave = object.toString();

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

} catch (FileNotFoundException e) {
    //做某事
} catch (IOException e) {
    //做某事
}

但通过上述代码,我意识到它会完全删除现有的 credentials.txt,这意味着我失去了 namegender 的值。有没有办法只替换 age?谢谢

英文:

Basically I am trying to overwrite the following JSON data

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

My goal is to replace only the age. So I am using FileOutputStream like below

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
}

But with the above code, I realized it completely deletes the existing credentials.txt which means I lost the name and gender value. Is there anyway just to replace the age? Thank you

答案1

得分: 0

基本上回答你的问题是否定的。你的操作步骤是:

  1. 将文件读入内存,
  2. 在内存中修改内容,
  3. 使用修改后的内容覆盖旧文件。

以下是有关如何修改文本文件的问题的答案链接:在Java中修改现有文件内容

英文:

Basically answer to your question is no. Your course of action is to

  1. read the file into memory,
  2. modify the content in memory
  3. override the old file with modified content.

Here is the question with good answers on how to modify a text file: Modifying existing file content in Java

答案2

得分: 0

我找到了答案。基本上,我需要读取现有的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);
    }
}
英文:

I've found the answer to this. Basically I need to read the existing JSON file and then replace the existing JSON object value

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

huangapple
  • 本文由 发表于 2023年6月12日 15:31:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定