BufferedWriter Class

How to use Java BufferedWriter The BufferedWriter class possesses the functionality of writing buffers of characters into a file. It extends Writer, which is an abstract class for writing to character streams . While using BufferedWriter, buffering can speed up IO quite a bit. Rather than write single character at a time to the source, the BufferedWriter writes a large amount of data at a time. So, it is typically much faster , especially for disk access and larger data amounts.

Advantage

When you want to write strings there are two options. The BufferedWriter and the File Writer .
  1. If you want to write one string the File Writer is better.
  2. If you want to write multiple strings, the BufferedWriter is more efficient.
While using BufferedWriter, the multiple strings can all be buffered together and as the default buffer size is 8192 characters this become just 1 system call to write. So the BufferedWriter needs to be cleared when called in the event there was something in the buffer. The following Java program writes an array into the external file using BufferedWriter.
import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { try { String weekdays[] = {"Monday", "Tuesday", "Wednsday", "Thursday", "Friday"}; File file = new File("D:/test.txt"); FileWriter fw = new FileWriter(file); BufferedWriter bw = new BufferedWriter(fw); for(int i=0;i<weekdays.length;i++){ bw.write(weekdays[i]); bw.newLine(); } bw.flush(); bw.close(); fw.close(); } catch (IOException e){ e.printStackTrace(); } } }

If you just want to print out the array like [a, b, c, ....], you can replace the loop with this one liner:

bw.write(Arrays.toString(weekdays));

How to append text to an existing file in Java?

The constructor FileWriter(file,true) append new content to the end of a file.
FileWriter fw = new FileWriter(file);

In the above code, all existing content will be overridden.

FileWriter fw = new FileWriter(file,true);
Above code keep the existing content and append the new content to the end of a file. The following Java program append the new content to the end of a file.
import java.util.*; import java.io.*; public class TestClass{ public static void main(String[] args) { try { String weekdays[] = {"Saturday", "Sunday"}; File file = new File("D:/test.txt"); FileWriter fw = new FileWriter(file,true); BufferedWriter bw = new BufferedWriter(fw); for(int i=0;i<weekdays.length;i++){ bw.write(weekdays[i]); bw.newLine(); } bw.flush(); bw.close(); fw.close(); } catch (IOException e){ e.printStackTrace(); } } }