Quickest way to append text to a file in Java


In Java, there are several different ways to append text in a file. For file operations, Java provides several classes. To appending text quickly you can use Files class.

Append text to file example:

try {
	Files.write(Paths.get("file1.txt"), "text to append".getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
	// To exception handling here
}

But above method will append only when the file already exists, it will not create a new file. It will throw NoSuchFileException. It will also not append any new line, you need to append by your self if required.

Append text to file example, with creating a new file:

try (FileWriter fw = new FileWriter(filename, true)) {
	// the true will append the new data
	fw.write("add a line\n");// appends the string to the file
} catch (IOException ioe) {
	System.err.println("IOException: " + ioe.getMessage());
}

Above will create a new file if a file does not exist otherwise it will append to end of the file.

File read-write is resource costally operation. If you are going to write several time or large data then you should use BufferedWriter class.

Example of BufferedWriter to append text:

String filename = "file1.txt";
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(filename, true)))) {
    out.println("the text");
} catch (IOException e) {
    System.err.println(e);
}

Or you can use Apache Commons 2.5 IO FileUtils class

Example:

FileUtils.writeStringToFile(file, "String to append", true);

There are many different ways to do this. Do it according to your need and choice.


Leave a Reply

Your email address will not be published. Required fields are marked *

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