Sorry, I think the 2nd method suggested by clankill3r works, and it works for text file that is not put in the sketch's local data folder, too.
Thanks, again!
// append a new line to an exisiting text file
import java.io.FileWriter;
import java.io.BufferedWriter;
void setup() {
// // method A
// // text file must be put in the sketch's local data folder
// try {
// // method A-1:
// String path = dataPath("test.txt");
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));
//
//// // method A-2:
//// File f = dataFile("test.txt");
//// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f, true)));
//
// out.println("\n");
// out.println("hello");
// out.flush();
// out.close();
// }
// catch (IOException e) {
// println(e);
// }
// method B:
// text file can be put in any folder relative to the sketch folder
String[] lines = loadStrings("../data/test.txt");
PrintWriter output = createWriter("../data/test.txt");
for (int i = 0; i < lines.length; i++) {
output.println(lines[i]);
}
output.println("\n");
output.println("hello");
output.flush();
output.close();
}
Answers
This is one way. The downside is that it doesn't look for the data folder so you need to provide a full path:
Here another way (untested):
If you have to append to a big file then the first one is probably a lot faster.
In order to access sketch's "data/" subfolder, we can rely on these 2 undocumented functions: :ar!
Let's say we've got a file named "someFile.txt" inside sketch's "data/" subfolder.
Then we can access it via the following ways: *-:)
String path = dataPath("someFile.txt");
File f = dataFile("someFile.txt");
P.S.: Calling flush() before close() is completely redundant! ;)
Dear clankill3r and GoToLoop, thank you very much for your advices!
However, it seems the 1st method suggested by clankill3r doesn't work if the text file is in the sketch's local data folder.
It must be adjusted as suggested by GoToLoop:
I want to ask if there is a way to read and append to a text file that is not put in the sketch's local data file.
Whereas for the 2nd method suggested by clankill3r, it will wipe out the existing text file and create a new one which is not what I want to do ...
Thanks and Happy New Year to you all! Joe
Sorry, I think the 2nd method suggested by clankill3r works, and it works for text file that is not put in the sketch's local data folder, too.
Thanks, again!
Here's my solution after reading about it @ http://StackOverflow.com: o=>
P.S.: Of course loadStrings() a file 1st, re-output() all, then append() new contents, and finally close() it, works as well, although it's slower! :P
Thank you very much, GoToLoop! I'll digest your suggestion later ...