I have a custom saving method I'm using in a project. Each time I call the method, I'm looking to have the next entry inserted in a new line in a text file.
For example, if I input "dog1" on the first method call then input "dog2" on the next method call. The output should be
dog1
dog2
Unfortunately dog2 overwrites dog1 so my text file output always contains a single entry.
Does anyone notice something off about my code? Thanks!
public void save(String filename, String st,
Context ctx) {
ArrayList<String[]> list = new ArrayList<>();
list.add(new String[] {st});
FileOutputStream fos;
try {
fos = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
OutputStreamWriter os= new OutputStreamWriter(fos);
String t = st;
for(String[] arr: list){
for(String s: arr){
os.write(s);
}
os.write(System.getProperty( "line.separator" ));
}
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
File reader method
public String read(String filename, Context ctx){
String tr="";
FileInputStream fis = null;
try {
fis=ctx.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder sb= new StringBuilder();
String text;
while((text=br.readLine())!=null){
sb.append(text);
tr = sb.toString();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try{
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return tr;
}