I have the following written in the onCreate() method of my main activity.
file = new File(this.getFilesDir(), SIMPLE_WORKOUTS);
writeToFile("Test1, 20, 10, 5, 2, 1", this);
writeToFile("Test2, 10, 5, 2, 1, 1", this);
writeToFile("Test3, 1, 1, 2, 3, 5", this);
String readFrom = readFromFile(this);
Log.e("TAG", readFrom);
However, the string readFrom is only ever equal to "Test3, 1, 1, 2, 3, 5". I want to be able to store multiple lines of code in a file, and read through the file line by line. The methods writeToFile and readFromFile are as follows:
public void writeToFile(String data, Context context) {
String existing = readFromFile(context);
try (OutputStreamWriter fos = new OutputStreamWriter(context.openFileOutput(SIMPLE_WORKOUTS, Context.MODE_PRIVATE))) {
fos.write(data + "\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput(SIMPLE_WORKOUTS);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = bufferedReader.readLine();
StringBuilder stringBuilder = new StringBuilder();
while ( receiveString != null ) {
stringBuilder.append(receiveString).append("\n");
receiveString = bufferedReader.readLine();
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Why the inputstreamreader is only reading the last line written to the file? Alternatively, would a Scanner be more suitable for my goal?