skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

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

  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search