How do I append text to a csv/txt file in Processing?

sfewfed picture sfewfed · Jun 9, 2013 · Viewed 10.5k times · Source

I use this simple code to write a few strings to the file called "example.csv", but each time I run the program, it overwrites the existing data in the file. Is there any way to append the text to it?

void setup(){
  PrintWriter output = createWriter ("example.csv");
  output.println("a;b;c;this;that ");
  output.flush();
  output.close();

}

Answer

Pwdr picture Pwdr · Jun 9, 2013
import java.io.BufferedWriter;
import java.io.FileWriter;

String outFilename = "out.txt";

void setup(){
  // Write some text to the file
  for(int i=0; i<10; i++){
    appendTextToFile(outFilename, "Text " + i);
  } 
}

/**
 * Appends text to the end of a text file located in the data directory, 
 * creates the file if it does not exist.
 * Can be used for big files with lots of rows, 
 * existing lines will not be rewritten
 */
void appendTextToFile(String filename, String text){
  File f = new File(dataPath(filename));
  if(!f.exists()){
    createFile(f);
  }
  try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
    out.println(text);
    out.close();
  }catch (IOException e){
      e.printStackTrace();
  }
}

/**
 * Creates a new file including all subfolders
 */
void createFile(File f){
  File parentDir = f.getParentFile();
  try{
    parentDir.mkdirs(); 
    f.createNewFile();
  }catch(Exception e){
    e.printStackTrace();
  }
}