Introduction
One of the most commonly used classes for writing text files is BufferedWriter. The BufferedWriter class belongs to the java.io package and writes characters to an output stream using an internal buffer. Instead of writing every character directly to the file, it stores data temporarily in memory and writes it in larger chunks. This reduces the number of disk write operations and significantly improves performance, especially when working with large files.
BufferedWriter is typically used with classes like FileWriter and OutputStreamWriter. It also provides convenient methods such as newLine() for writing platform-independent line separators.
What is BufferedWriter?
BufferedWriter is a Java class used to write text efficiently by buffering characters before writing them to the output destination.
Package:
import java.io.BufferedWriter;
It is commonly used with:
- FileWriter
- OutputStreamWriter
Unlike FileWriter, which writes characters directly to a file, BufferedWriter collects data in memory and writes it in larger blocks, resulting in better performance.
Why Use BufferedWriter?
Using BufferedWriter provides several benefits:
- Faster writing performance
- Reduced disk access
- Efficient for large text files
- Supports writing complete lines
- Easy integration with FileWriter
- Suitable for log files and reports
It is one of the preferred classes for writing text data in Java applications.
How BufferedWriter Works?
When you write data using BufferedWriter, the characters are first stored in an internal memory buffer.
Once the buffer becomes full, or when you explicitly call flush() or close(), the buffered data is written to the file.
This approach minimizes the number of write operations and improves overall application performance.
Creating a BufferedWriter
The most common way is to wrap a FileWriter.
Syntax
BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"));
Here:
- FileWriter handles the connection to the file.
- BufferedWriter adds buffering for efficient writing.
Writing Text to a File
The write() method writes text to the file.
Example
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"));
writer.write("Rahul");
writer.newLine();
writer.write("Amit");
writer.newLine();
writer.write("Priya");
writer.close();
System.out.println("File written successfully.");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Output
The file students.txt will contain:
Rahul
Amit
Priya
Appending Data to a File
By default, FileWriter overwrites the existing file.
To append data, enable append mode.
BufferedWriter writer =
new BufferedWriter(
new FileWriter("students.txt", true)
);
writer.newLine();
writer.write("Neha");
writer.close();
The existing file remains unchanged, and the new data is added at the end.
Writing Characters
BufferedWriter can write individual characters.
BufferedWriter writer =
new BufferedWriter(new FileWriter("letters.txt"));
writer.write('A');
writer.write('B');
writer.write('C');
writer.close();
Output
Writing a Portion of a Character Array
The write() method can write characters from an array.
char[] letters = {'J', 'A', 'V', 'A'};
BufferedWriter writer =
new BufferedWriter(new FileWriter("word.txt"));
writer.write(letters);
writer.close();
Output
Writing Platform-Independent New Lines
Use the newLine() method.
writer.write("Java");
writer.newLine();
writer.write("Programming");
Using newLine() is preferable to manually writing “\n” because it automatically uses the correct line separator for the operating system.
Common BufferedWriter Methods
write()
Writes text or characters.
writer.write("Hello");
newLine()
Writes a platform-independent line separator.
writer.newLine();
flush()
Forces buffered data to be written immediately.
writer.flush();
Use this when you need the data to appear in the file before closing the stream.
close()
Closes the stream and releases system resources.
writer.close();
This also flushes any remaining buffered data.
Using try-with-resources (Recommended)
The recommended approach is to use try-with-resources.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try (BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"))) {
writer.write("Java BufferedWriter Example");
} catch(IOException e) {
e.printStackTrace();
}
}
}
The stream is automatically closed, even if an exception occurs.
BufferedWriter vs FileWriter
| BufferedWriter | FileWriter |
|---|---|
| Uses an internal buffer | Writes directly to the file |
| Faster | Slower |
| Supports newLine() | Does not provide readLine() |
| Efficient for repeated writes | Suitable for simple writing |
| Better performance | Simpler API |
Real-Life Example
Suppose an application generates a daily sales report.
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class SalesReport {
public static void main(String[] args) {
try (BufferedWriter writer =
new BufferedWriter(new FileWriter("sales.txt"))) {
writer.write("Daily Sales Report");
writer.newLine();
writer.write("Total Orders: 150");
writer.newLine();
writer.write("Revenue: $25,000");
} catch(IOException e) {
e.printStackTrace();
}
}
}
Many business applications generate reports using BufferedWriter because it efficiently handles multiple write operations.
Advantages of BufferedWriter
- High writing performance
- Reduces disk I/O operations
- Efficient for large text files
- Easy to use
- Supports platform-independent new lines
- Integrates with FileWriter and OutputStreamWriter
- Suitable for logs, reports, and exported text files
Limitations of BufferedWriter
- Works only with character data
- Not suitable for binary files
- Requires proper exception handling
- Buffered data is not written until the buffer is flushed or the stream is closed
Common Mistakes
1. Forgetting to Close the Writer
Incorrect:
BufferedWriter writer =
new BufferedWriter(new FileWriter("students.txt"));
Correct:
writer.close();
Or use try-with-resources.
2. Forgetting to Flush Data
If the writer remains open, recently written data may still be in the buffer.
writer.flush();
Calling flush() ensures that buffered data is written immediately.
3. Accidentally Overwriting Existing Data
Incorrect:
new FileWriter("students.txt");
Correct:
new FileWriter("students.txt", true);
Use append mode when you want to preserve existing content.
4. Using BufferedWriter for Binary Files
Incorrect:
BufferedWriter writer =
new BufferedWriter(new FileWriter("image.png"));
Use FileOutputStream or BufferedOutputStream for binary data.
Best Practices
- Use BufferedWriter for writing large text files.
- Prefer newLine() over manually writing newline characters.
- Always use try-with-resources.
- Call flush() when data must be written immediately.
- Handle IOException properly.
- Use append mode when updating existing files.
- Use byte streams for binary files.
Conclusion
The Java BufferedWriter class is one of the most efficient tools for writing text files. By buffering character data before writing it to the file system, it reduces I/O operations and delivers significantly better performance than writing characters directly. Its support for methods such as write(), newLine(), flush(), and close() makes it simple to generate reports, save application data, create log files, and export text efficiently.
For modern Java applications, BufferedWriter is the preferred choice for writing large amounts of text. By following best practices—such as using try-with-resources, flushing data when necessary, enabling append mode when appropriate, and using byte streams for binary data—you can build reliable, high-performance Java applications that handle file output effectively.