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
I've found the answer to this. Basically I need to read the existing JSON file and then replace the existing JSON object value
Basically answer to your question is no. Your course of action is to
Here is the question with good answers on how to modify a text file: Modifying existing file content in Java