In this lesson, you will learn
The java.io.BufferedWriter class in Java is a character output stream that buffers characters before writing them to the underlying stream (like a file writer).
This buffering mechanism significantly improves the efficiency of writing operations, especially when dealing with a large number of small write requests.
| Constructor | Description | Throws |
|---|---|---|
BufferedWriter(Writer out) |
Creates a buffered character-output stream using a default buffer size which is 8192 characters (8 KB). | NullPointerException if out is null |
BufferedWriter(Writer out, int sz) |
Creates a buffered character-output stream using a specified buffer size. | NullPointerException if out is null <br> IllegalArgumentException if sz is non-positive |
package inputoutput;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample1 {
public static void main(String[] args) {
String filePath = "output1.txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("This is the first line of text.");
writer.newLine(); // Writes the platform-specific line separator
writer.write("This is the second line.");
writer.newLine();
writer.write("End of the content.");
// No explicit flush() needed here as try-with-resources will close the writer, which implicitly flushes.
System.out.println("Data written to " + filePath + " successfully.");
} catch (IOException e) {
System.err.println("Error writing to file: " + e.getMessage());
}
}
}
Data written to output1.txt successfully.
package inputoutput;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriterExample2 {
public static void main(String[] args) {
String filePath = "existing_file.txt";
try (BufferedWriter writer = new BufferedWriter
(new FileWriter(filePath, true))) { // true for append mode
writer.newLine(); // Add a newline before appending
writer.write("This text is appended to the file.");
System.out.println("Data appended to " + filePath + " successfully.");
} catch (IOException e) {
System.err.println("Error appending to file: " + e.getMessage());
}
}
}
Data appended to existing_file.txt successfully.
Explanation:
FileWriter with the append parameter set to true. This tells the FileWriter to add new content to the end of the file instead of overwriting it.BufferedWriter for efficient writing.