I want to rewrite my JSON file with my edited jsonObj. When I set the 2nd parameter by the FileOutputStream to true, I get a output which is appended to the file. But I want to rewrite this, how can I do it?
When I set the 2nd parameter to false, myReader is null and I don’t get a output.
File myFile = new File(Environment.getExternalStorageDirectory().getPath() + filepath); FileOutputStream out = new FileOutputStream(myFile, false); OutputStreamWriter myOutWriter = new OutputStreamWriter(out); String output = ""; FileInputStream fIn = new FileInputStream(myFile); BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn, StandardCharsets.UTF_8.name())); String line; while ((line = myReader.readLine()) != null) { output += line; } JSONObject jsonObj = new JSONObject(output); jsonObj.put("test", "hi"); myOutWriter.write(jsonObj.toString()); myOutWriter.close(); out.close();
Advertisement
Answer
You are trying to write and read to the same file at the same time in “overwrite mode”.
Once you execute FileOutputStream out = new FileOutputStream(myFile, false);
the file is immediately emptied (truncated to 0).
So trying to read from it will not work, as there will be nothing to read.
Change the order of your code – read the file to memory fist, close the reader, then open for writing.