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