0

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;
}
Javaing
  • 47
  • 6
  • Possible duplicate of [How to append text to an existing file in Java](https://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java) – PPartisan May 13 '19 at 15:21

1 Answers1

0

Declare ArrayList globally or outside the save method. Because every time on call save() method new object create for list and override previous data with new data instead of add new data on list.

 Declare below line outside save() method or globally
 ArrayList<String[]> list= new ArrayList<>();
Dharmender Manral
  • 1,504
  • 1
  • 6
  • 7