We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › appending to a text file
Page Index Toggle Pages: 1
appending to a text file (Read 602 times)
appending to a text file
Jun 5th, 2009, 7:22am
 
I wish to be able to open a text file for logging and append records to the end of the file. I cant get the syntax right. In the eg below I use createWriter, however as it name implies it overwrites the previous version.

------------------
static String aFile = "test.txt";
PrintWriter output;

void setup() {
 output = createWriter(aFile);
}

void draw() {

 output.println("blahblah");
}

void keyPressed() {

 output.flush();
 output.close();
 exit();  
}
Re: appending to a text file
Reply #1 - Jun 5th, 2009, 8:06am
 
Looks like the case isn't handled.
Two solutions:
- Read the whole file, re-create it with new stuff. Quite impractical...
- Use the following:

Code:
PrintWriter appendWriter(String filename) {
   try {
File file = saveFile(filename);
OutputStream output = new FileOutputStream(file, true);
return createWriter(output);
   } catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Couldn't create a writer for " +
filename);
   }
}

Warning: not tested!
That's a variant of the code of createWriter as found in PApplet.java.
The key is the true parameter given to the FileOutputStream constructor, telling it to append.
Page Index Toggle Pages: 1