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 › Append to a text file
Page Index Toggle Pages: 1
Append to a text file (Read 1280 times)
Append to a text file
Mar 4th, 2010, 9:40pm
 
Is there any way to append to the end of a text file using PrintWriter? The only way I can think of (without going into Java methods) is to load the textfile into an array (loadStrings) and then write it back into the file and then write the new element at the end. Not very elegant....

Code:

PrintWriter output;


void setup()
{
 String lines[] = loadStrings("test.txt");
 output=createWriter("test.txt");
 for(int i=0; i<lines.length ; i++)
 {
   output.println(lines[i]);
 }
 output.println("Testing...testing...");
 output.flush();
 output.close();
}

void draw() {}


Running this repeatedly does add another line to the end of the text file every time....
Re: Append to a text file
Reply #1 - Mar 4th, 2010, 10:08pm
 
http://processing.org/discourse/yabb2/num_1251025598.html
that will help
Re: Append to a text file
Reply #2 - Mar 5th, 2010, 8:06am
 
Thanks...I might use that method. I'm wondering if it really is less expensive though - "append" probably has to load the text file into memory anyway to append to it?

I guess it is the writing part that is  more expensive...
Re: Append to a text file
Reply #3 - Mar 5th, 2010, 8:40am
 
Quote:
"append" probably has to load the text file into memory anyway to append to it?

No. The system probably offers an append mode to file writing, just adding data after data existing on disk. That append option leverages this capability, thus is much more efficient, particularly on large files.

Note: you can use yet another method, falling back on good old PrintWriter, which has the advantage to offer println (no worries about line ending) and printf (formatting), among other things:
Code:
PrintWriter pw = null;
try
{
pw = new PrintWriter(new BufferedWriter(new FileWriter(outFileName, true))); // true means: "append"
pw.println(newData);
}
catch (IOException e)
{
// Report problem or handle it
}
finally
{
if (pw != null)
{
pw.close();
}
}
Re: Append to a text file
Reply #4 - Mar 5th, 2010, 1:49pm
 
Very useful, thanks.
Page Index Toggle Pages: 1