How to append a text to a file

edited July 2015 in How To...

Hi there,

As seen in SaveFile2 in the example, you can save a file with PrintWriter like:

PrintWriter output = createWriter("log.txt"); output.println("This is a log"); output.flush(); output.close();

However, log.txt will be overwritten when you run this code twice. Does anyone know how to "append" text to a file?

Best..Yui

Answers

  • edited July 2015

    @ arco=== that is easy::

        import java.io.FileWriter;
        import java.io.*;
        FileWriter fw;
        BufferedWriter bw;
        void keyPressed() { // Press a key to save the data
    
         try{
                  File file =new File(chemin+"/positions.txt");
        //chemin = dataPath;
        // positions.txt== your file;
    
                  if(!file.exists()){
                    file.createNewFile();
                  }
    
                  FileWriter fw = new FileWriter(file,true);///true = append
                  BufferedWriter bw = new BufferedWriter(fw);
                  PrintWriter pw = new PrintWriter(bw);
    
                  pw.write("hello world!!!!! j'ajoute something au txt");
    
                  pw.close();
    
    
               }catch(IOException ioe){
                   System.out.println("Exception ");
                   ioe.printStackTrace();
              }
           }
    
  • Thank you akenaton,

    For readers, I should paste working example.

    import java.io.FileWriter;
    import java.io.*;
    FileWriter fw;
    BufferedWriter bw;
    void keyPressed() { // Press a key to save the data
      try {
        File file =new File("/users/kitayui/desktop/test.txt");
        //chemin = dataPath;
        // positions.txt== your file;
    
        if (!file.exists()) {
          file.createNewFile();
        }
    
        FileWriter fw = new FileWriter(file, true);///true = append
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);
    
        pw.write("hello world!!!!! j'ajoute something au txt");
    
        pw.close();
      }
      catch(IOException ioe) {
        System.out.println("Exception ");
        ioe.printStackTrace();
      }
    }
    
    
    void draw() {
    }
    
Sign In or Register to comment.