We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I have the following function to append a new line to an existing text file. But it doesn't seem to be efficient as it re-reads and re-writes every line each time I add a new line, especially when I need to append a lot of new lines. Can you advise an efficient way to do this? Thank you!
// general function of appending a new line of text to an existing text file
void appendNewLine (String _fileName, String _newLine) {
// http://forum.processing.org/two/discussion/comment/33698
// method B:
// text file can be put in any folder relative to the sketch folder
String[] lines = loadStrings(_fileName);
// create a copy of the existing file
PrintWriter output = createWriter(_fileName);
// write the contents of the existing file to the new one
for (int i = 0; i < lines.length; i++) {
output.println(lines[i]);
}
// append new contents to the new file
//output.println("\n");
output.println(_newLine);
//output.flush(); // might be redundant
output.close();
}
Answers
You should look at PrintWriter class definition and instantiate 1 by yourself w/o autoFlush:
https://docs.oracle.com/javase/8/docs/api/index.html
And yes, flush() method is redundant when it's just before close() b/c close() calls flush()! :-\"
Use the search, Luke: https://www.google.fr/search?as_sitesearch=processing.org&as_q=append+to+text+file
(simple query from the main site...)
Thanks, GoToLoop and PhiLho!
The following code is based on your early post on the same question.
However, I couldn't get it work when I call the appendNewLine() function from places other than inside the fileSelected() function
It seems while the program is waiting for input for file selection, the process has moved forward to the appendNewLine() function which doesn't have the inputs yet ...
What I want is that once the file is selected, I can add new lines to it anytime I want later.
Can you kindly tell me what I'm doing wrong over here?
Thanks!
Thanks, GoToLoop!
I found out that selectInput() will run on a separate thread which might be causing the problem.
The following also put the appendNewLine() function inside an event triggered function