Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append to file android

Tags:

java

android

hey there, i need to append to my file but it is not working, it keeps overwriting the file, can anyone please tell me what is wrong:

  public void generateNoteOnSD(String sBody){

        try
        {
            File root = new File(Environment.getExternalStorageDirectory(), "AdidasParticipants");

            if (!root.exists()) {
                root.mkdirs();

            }

            File gpxfile = new File(root, "participants.txt");

            BufferedWriter bW;

            bW = new BufferedWriter(new FileWriter(gpxfile));
            bW.write(sBody);
            bW.newLine();
            bW.flush();
            bW.close();
            //Toast.makeText(mContext, "Tus datos han sido guardados", Toast.LENGTH_SHORT).show();
        }
        catch(IOException e)
        {
             e.printStackTrace();
          //   importError = e.getMessage();
            // iError();
        }
       } 

Thanks in advance.

like image 735
Carlos Barbosa Avatar asked May 13 '11 03:05

Carlos Barbosa


People also ask

How do I append to a file?

You do this by using the append redirection symbol, ``>>''. To append one file to the end of another, type cat, the file you want to append, then >>, then the file you want to append to, and press <Enter>.

How do you append one file to another in Java?

Example 2: Append text to an existing file using FileWriterWhen creating a FileWriter object, we pass the path of the file and true as the second parameter. true means we allow the file to be appended. Then, we use write() method to append the given text and close the filewriter.

How do you append a line in Java?

Append a single line to a file – Files.write(path, content. getBytes(StandardCharsets. UTF_8), StandardOpenOption. APPEND);


1 Answers

You can fix it by changing the line where you assign the BufferedWriter:

bW = new BufferedWriter(new FileWriter(gpxfile, true));

When you open a file using the FileWriter constructor that only takes in a File, it will overwrite what was previously in the file. Supplying the second parameter as true tells the FileWriter that you want to append to the end of it.

like image 193
nicholas.hauschild Avatar answered Oct 05 '22 23:10

nicholas.hauschild