We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, I need to append data to a text file - is it true that this can not be done directly in processing. I found the following code below that uses proper java but i get an error "the function println(String) does not exist" when trying to run it in processing.
Any help is much appreciated.
Cheers.
import java.io.BufferedWriter;
import java.io.FileWriter;
try {
FileWriter output = new FileWriter("example.txt",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();
}
Answers
I haven't found any method called println() in FileWriter either: :O)
http://docs.oracle.com/javase/6/docs/api/java/io/FileWriter.html
But there's a write() method there though! :ar!
Not sure where you found out this code, but it is a typical example of bad I/O management in Java that you can find all over the Internet, including in the old forums... And, then, alas, in real code in production!
It isn't really very important for small sketches with limited lifetime (as opposed to servers that can run for days), but the proper way to close a stream is:
I omitted the flush() because the close() does it automatically.
The difference here is that if an I/O exception happens (incorrect name, cannot create file, etc.), the file writer is properly closed, while it would remain opened in the old code.
Yes, the syntax is heavy (it is better in Java 7!), but necessary.
It was an intervention of the committee against the propagation of bad code. :-)
Oh, I removed the import of BufferedWriter, but if you write lot of data, you better use it to avoid poor performance. Code is almost the same: