Java BufferedWriter

Efficient text writing with buffering capabilities

✍️ What is BufferedWriter?

BufferedWriter writes text efficiently by buffering characters in memory before writing to files. It's ideal for writing large amounts of text with improved performance.


// Basic BufferedWriter example
import java.io.*;

BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"));
bw.write("Hello World!");
bw.close();
                                    

Result:

Creates 'output.txt' with "Hello World!"

BufferedWriter Features

📝

Text Writing

Write text files efficiently

bw.write("Hello World!");

Buffered Output

Faster writing with buffer

BufferedWriter bw = new BufferedWriter(writer);
📄

Line Writing

Write lines with newlines

bw.newLine();
💾

Force Write

Flush buffer to disk

bw.flush();

🔹 Basic BufferedWriter Usage

Here's how to write to a text file using BufferedWriter:

import java.io.*;

public class BufferedWriterExample {
    public static void main(String[] args) {
        try {
            // Create BufferedWriter
            FileWriter fw = new FileWriter("report.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            
            // Write content
            bw.write("Daily Report");
            bw.newLine();
            bw.write("=============");
            bw.newLine();
            bw.write("Tasks completed: 5");
            bw.newLine();
            bw.write("Status: Success");
            
            // Close the writer
            bw.close();
            System.out.println("Report written successfully!");
            
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Report written successfully!

File 'report.txt' contains formatted report

🔹 Try-with-Resources

Modern approach with automatic resource management:

import java.io.*;

public class ModernBufferedWriter {
    public static void main(String[] args) {
        // Automatic resource management
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("notes.txt"))) {
            
            // Write multiple lines
            String[] notes = {
                "Java I/O is powerful",
                "BufferedWriter improves performance",
                "Always close your streams",
                "Try-with-resources is recommended"
            };
            
            for (String note : notes) {
                bw.write("• " + note);
                bw.newLine();
            }
            
            System.out.println("Notes saved successfully!");
            
        } catch (IOException e) {
            System.out.println("Writing error: " + e.getMessage());
        }
        // BufferedWriter is automatically closed
    }
}

Output:

Notes saved successfully!

File contains bulleted list of notes

🔹 Append Mode

Add content to existing files without overwriting:

import java.io.*;
import java.time.LocalDateTime;

public class AppendExample {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("log.txt", true))) {
            
            // Add timestamp and log entry
            String timestamp = LocalDateTime.now().toString();
            bw.write("[" + timestamp + "] Application started");
            bw.newLine();
            bw.write("[" + timestamp + "] User logged in");
            bw.newLine();
            
            // Force write to disk
            bw.flush();
            
            System.out.println("Log entries added!");
            
        } catch (IOException e) {
            System.out.println("Logging error: " + e.getMessage());
        }
    }
}

Output:

Log entries added!

Timestamped entries appended to 'log.txt'

🔹 Writing Large Data

BufferedWriter excels at writing large amounts of text:

import java.io.*;

public class LargeDataWriter {
    public static void main(String[] args) {
        try (BufferedWriter bw = new BufferedWriter(new FileWriter("data.csv"))) {
            
            // Write CSV header
            bw.write("ID,Name,Age,City");
            bw.newLine();
            
            // Write 1000 records
            for (int i = 1; i <= 1000; i++) {
                String record = i + ",User" + i + "," + (20 + i % 50) + ",City" + (i % 10);
                bw.write(record);
                bw.newLine();
                
                // Flush every 100 records
                if (i % 100 == 0) {
                    bw.flush();
                    System.out.println("Written " + i + " records...");
                }
            }
            
            System.out.println("CSV file created successfully!");
            
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Output:

Written 100 records...

Written 200 records...

...

CSV file created successfully!

🔹 Custom Buffer Size

Optimize performance with custom buffer size:

import java.io.*;

public class CustomBufferWriter {
    public static void main(String[] args) {
        try {
            // Create BufferedWriter with 16KB buffer
            FileWriter fw = new FileWriter("bigfile.txt");
            BufferedWriter bw = new BufferedWriter(fw, 16384);
            
            // Write large content
            for (int i = 0; i < 10000; i++) {
                bw.write("This is line number " + i + " with some content.");
                bw.newLine();
            }
            
            bw.close();
            System.out.println("Large file written with custom buffer!");
            
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

🔹 Common Methods

Important BufferedWriter methods:

  • write(String s) - Writes a string
  • write(char[] cbuf) - Writes character array
  • write(int c) - Writes single character
  • newLine() - Writes system line separator
  • flush() - Forces write of buffered data
  • close() - Closes the writer
// Method examples
BufferedWriter bw = new BufferedWriter(new FileWriter("example.txt"));

bw.write("Hello");                // Write string
bw.write(' ');                    // Write single character
bw.write("World!");               // Write another string
bw.newLine();                     // Add line break
bw.flush();                       // Force write to disk
bw.close();                       // Always close!

🧠 Test Your Knowledge

Which method should you call to ensure all buffered data is written to the file?