I am writing a text file to internal storage in android to save some settings. I believe that the write to file function is working properly, but when I re-read in the file (even directly after writing) the file is empty. I have gone through several other questions/answers on Stack overflow and none of them are solving my problem.
private void saveOtherData() {
JSONObject settingsJson = new JSONObject();
try {
OutputStreamWriter writer;
File testFile = new File(userProfile.this.getFilesDir(), "settings.txt");
if (!testFile.exists()) {
testFile.createNewFile();
testFile.mkdir();
}
writer = new OutputStreamWriter(userProfile.this.openFileOutput("settings.txt", Context.MODE_PRIVATE));
--code that adds a bunch of data to settingsJson
writer.write(settingsJson.toString());
//this line shows that settingsJson has the values I want
System.out.println(settingsJson);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException ex) {
ex.printStackTrace();
}
The following code is run directly after the above code. But while ((line = br.readLine()) != null)
is always null, which I assume means that the text file is empty.
//test the file reader
try {
JSONObject settings;
String jsonCode = "";
StringBuilder text = new StringBuilder();
File file = new File(userProfile.this.getFilesDir(), "settings.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas on what is going wrong?