Java/JavaScript Tips on Append to File

This is Java/JavaScript Tips on Append content to file. I will introduce append file via command line, Java, and Node.JS (JavaScript).

To append file via command line, in Windows or Unix, you can do:

echo "test" >> a.txt

The file a.txt will be created if not exist at the first time. And the subsequence calls of >> will append the content to next line of the end of file.

To append file via Java, you can do:

PrintWriter pw = new PrintWriter(new FileWriter(new File("a.txt"), true)); 
pw.println("test");
pw.close();

The file a.txt will be created if not exist at the first time. And the subsequence calls of PrintWriter.println will append the content to next line of the end of file.

The interesting thing is I like to use PrintWriter, to call println, which I not need to append \n myself.

Notice the true variable at new FileWriter, this let Java know you want to append file, if you not provide this variable, Java will always overwrite the file but not appending.

To append file via JavaScript, you can do:

in asynchronous calls:

var fs = require('fs');
fs.appendFile('a.txt', 'content\n', function(err) {
 // some callback after append file
});

OR

in synchronize calls:

var fs = require('fs');
fs.appendFileSync('a.txt', 'content\n');

The file a.txt will be created if not exist at the first time. And the subsequence calls of appendFile or appendFileSync will append the content to next line of the end of file.

Node.JS provides asynchronous and synchronize versions for each File IO Calls. Refer the link here. Other than appendFile, for example, readFile/readFileSync, writeFile/writeFileSync.

Node.JS itself is a single threaded and asynchronous. It is always recommended to use asynchronous version of method instead of synchronize version, as synchronize version is a blocking calls. If the content need append to file is very very big, the calls will just hang there, Node.JS cannot handle other requests anymore. To learn how Node.JS back end works, refer here.

Author: fyhao

Jebsen & Jessen Comms Singapore INTI University College Bsc (Hon) of Computer Science, Coventry University

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.