BufferedWriter
is a wrapper class around another Writer
class (like FileWriter
) that buffers output characters to provide efficient writing of characters, arrays, and strings. It reduces the number of physical write operations by buffering data internally, improving performance, especially when writing large text files or multiple small writes.
Commonly Used Constructors and Methods


Simple Program: Write Text to File Using BufferedWriter
Write multiple lines of text to a file output.txt
efficiently using BufferedWriter
.
import java.io.*; public class BufferedWriterSimpleDemo { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { bw.write("Hello, BufferedWriter!"); bw.newLine(); bw.write("This is a simple example."); bw.newLine(); bw.write("Writing lines to a file efficiently."); } catch (IOException e) { e.printStackTrace(); } } }
Problem Statement:
LotusJavaPrince needs to implement a logging system where Mahesh suggests using BufferedWriter
to write log messages efficiently to a file called app.log
. The program writes several log entries and flushes the buffer periodically.
import java.io.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LoggerSystem { private static final String LOG_FILE = "app.log"; public static void logMessage(String message) { try (BufferedWriter bw = new BufferedWriter(new FileWriter(LOG_FILE, true))) { String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); bw.write(timestamp + " - " + message); bw.newLine(); bw.flush(); // Ensure message is written immediately } catch (IOException e) { System.out.println("Error writing to log file."); e.printStackTrace(); } } public static void main(String[] args) { logMessage("Application started."); logMessage("User login successful."); logMessage("Data processed successfully."); logMessage("Application ended."); } }
The BufferedWriter
class is a powerful and efficient way to write character data to files or other output streams in Java. By buffering output internally, it minimizes costly physical write operations, making programs faster and more resource-friendly, especially when writing large amounts of data or multiple small pieces of text.
The program appends timestamped log messages to a file called app.log
. After running, the app.log
file will contain entries like:
2025-05-30 14:45:01 - Application started.
2025-05-30 14:45:01 - User login successful.
2025-05-30 14:45:01 - Data processed successfully.
2025-05-30 14:45:01 - Application ended.
Code language: CSS (css)