BufferedWriter Class in Java

BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.
newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator. Not all platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a newline character directly.
In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters. 
For example,
 PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

BufferedWriter class Constructors

  • BufferedWriter(Writer out) - Creates a buffered character-output stream that uses a default-sized output buffer.
  • BufferedWriter(Writer out, int sz) - Creates a new buffered character-output stream that uses an output buffer of the given size.

BufferedWriter class Methods

  • void close() - Closes the stream, flushing it first.
  • void flush() - Flushes the stream.
  • void newLine() - Writes a line separator.
  • void write(char[] cbuf, int off, int len) - Writes a portion of an array of characters.
  • void write(int c) - Writes a single character.
  • void write(String s, int off, int len) - Writes a portion of a String.

BufferedWriter class Example

Let's see the simple example of writing the data to a text file sample.txt using Java BufferedWriter.
This example uses the try-with-resources statement to close the resources automatically.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

 * The class demonstrate the usage of BufferedWriter class methods.
 * @author javaguides.net

public class BufferedWriterExample {
 public static void main(String[] args) {
  try (FileWriter writer = new FileWriter("D:\\sample.txt");
    BufferedWriter buffer = new BufferedWriter(writer);) {
   buffer.write("Welcome to JavaGuides.");
  } catch (IOException e) {



Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course