6

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();

}
Vishal Zanzrukia
  • 4,902
  • 4
  • 38
  • 82
Faridoon
  • 154
  • 2
  • 4
  • 8

3 Answers3

9
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();
  }
}    
Pwdr
  • 3,712
  • 4
  • 28
  • 38
  • Note this is no longer Processing, but is now plain Java with embedded Processing (i.e. this will not work in enviroments that can run Processing code, but don't know anything about Java) – Mike 'Pomax' Kamermans Jun 09 '13 at 19:08
  • 1
    Processing is based on Java, this code runs fine within the Processing IDE! – Pwdr Jun 09 '13 at 19:10
  • Yes, and it'll break when compiled by Processing.js (or other Processing compilers that generate code for not-in-a-JVM), which has full Processing support, but doesn't run in a JVM, and so has no idea what Java is =) – Mike 'Pomax' Kamermans Jun 09 '13 at 19:15
  • Yes, this won’t work with processing.js. But I think there is no build-in solution which can be compiled as a Processing Sketch (Java) **and** processing.js (Javascript). – Pwdr Jun 09 '13 at 19:18
  • @Pwdr could I ask, how could a append text and maintain the line count? So that new text is added in rows, not lines? eg: (Text 0 , 1, 2) – justachap Jan 13 '14 at 08:25
  • @justachap I don’t really get your question… – Pwdr Jan 13 '14 at 18:45
  • @Pwdr at the moment when the sketch is run with the code you kindly shared, the text file updates by adding more lines to file. So the first time you run it, it has 1-10 lines, then the second time, 20 lines etc. I was wondering if there was a way to maintain the first 10 lines but then add to them on a per line bases, so no matter how many times you run the sketch, there will always be 10 lines, but with how ever many columns you have run the sketch. I hope that makes sense? – justachap Jan 13 '14 at 18:57
  • @justachap It would be better here to read in the whole file and to rewrite it every time you add something new. Just adding columns without touching the rest is not possible afaik. You should have a look at the [Table Examples](http://www.processing.org/reference/Table.html) – Pwdr Jan 14 '14 at 08:14
0

You have to use a FileWriter (pure Java (6 or 7)) rather than PrintWriter from the Processing API. FileWriter has a second argument in it's constructor that allows you to set a Boolean to decide whether you will append the output or overwrite it (true is to append, false is to overwrite).

The documentation is here: http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html Note you can also use a BufferedWriter, and pass it a FileWriter in the constructor if that helps at all (but I dont think it's necessary in your case).

Example:

try {
  FileWriter output = new FileWriter("example.csv",true); //the true will append the new data
  output.println("a;b;c;this;that ");
  output.flush();
  output.close();
}
catch(IOException e) {
  println("It Broke :/");
  e.printStackTrace();
}

As above, this will work in the PDE - and in Android - but if you need to use it in PJS, PyProcessing, etc, then you will have to hack it

  • dynamically read the length of the existing file and store it in an ArrayList
  • add a new line to the ArrayList
  • use the ArrayList index to control where in the file you are currently writing

If you want to suggest an enhancement to the PrintWriter API (which is probably based off of FileWriter), you can do so at Processing's Issue page on GitHub:

https://github.com/processing/processing/issues?state=open

jesses.co.tt
  • 2,689
  • 1
  • 30
  • 49
-1

Read in the file's data, append your new data to that, and write the appended data back to the file. Sadly, Processing has no true "append" mode for file writing.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
  • it certainly won't, I never said it was a great solution, but if you want to stay inside the Processing language, this is all there is. (Of course, you can feature request append-writing on the Processing github page) – Mike 'Pomax' Kamermans Jun 09 '13 at 19:07
  • Do these things how? – Alex Hall Oct 31 '19 at 23:06
  • See https://processing.org/reference/ for the how, and https://github.com/processing/processing/issues for filing an issue. – Mike 'Pomax' Kamermans Nov 01 '19 at 03:44
  • Mike, surely you know that standard answer format at stackoverflow is to detail specifics of how to do something, exactly, step by step and line by line of code. Your answer is general and offers no specific help on _how exactly_ to accomplish the goal stated in the question. Fortunately other answers here do. – Alex Hall Nov 06 '19 at 06:52
  • You mean like _all the code examples that the excellent Processing documentation gives you_? Yes I'm sure it's very hard to read through those, six years after someone else asked this. A person who, based on the code they showed, knows full well how to do each of those things. If you don't, and you just started with Processing, then as the former maintainer of Processing.js I strongly advise you to read through the official Processing tutorials and reference documentation. Both as part of your own [searching and researching](/help/how-to-ask), and because they're excellent resources in general – Mike 'Pomax' Kamermans Nov 06 '19 at 18:24