How to Use BufferedWriter in Java: Simple Guide and Example
Use
BufferedWriter in Java by wrapping it around a FileWriter to write text to files efficiently. Create a BufferedWriter object, use its write() method to add text, and always close it to save and release resources.Syntax
The basic syntax to use BufferedWriter is to create it by passing a Writer like FileWriter to its constructor. Then, use write() to add text and close() to finish writing and free resources.
BufferedWriter bw = new BufferedWriter(new FileWriter("filename.txt"));creates the writer.bw.write("text")writes text to the buffer.bw.close()flushes and closes the writer.
java
BufferedWriter bw = new BufferedWriter(new FileWriter("filename.txt")); bw.write("Hello, world!"); bw.close();
Example
This example shows how to write multiple lines to a file using BufferedWriter. It demonstrates opening the writer, writing lines, and closing it properly.
java
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) { bw.write("First line"); bw.newLine(); bw.write("Second line"); bw.newLine(); bw.write("Third line"); } catch (IOException e) { System.out.println("Error writing file: " + e.getMessage()); } } }
Common Pitfalls
Common mistakes when using BufferedWriter include forgetting to close the writer, which can cause data loss, and not handling IOException. Also, writing without flushing or closing means the text may not be saved to the file.
Always use try-with-resources or close the writer in a finally block to ensure resources are freed.
java
/* Wrong way: forgetting to close BufferedWriter */ BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")); bw.write("Hello"); // bw.close() missing - data may not be saved /* Right way: using try-with-resources */ try (BufferedWriter bw2 = new BufferedWriter(new FileWriter("file.txt"))) { bw2.write("Hello"); } catch (IOException e) { e.printStackTrace(); }
Quick Reference
- BufferedWriter(Writer out): Wraps a Writer to buffer output.
- write(String s): Writes a string to the buffer.
- newLine(): Writes a platform-specific newline.
- flush(): Forces buffered output to be written.
- close(): Flushes and closes the stream.
Key Takeaways
Always close BufferedWriter to ensure data is saved and resources are released.
Use try-with-resources to handle closing automatically and avoid resource leaks.
BufferedWriter buffers output for efficient writing to files.
Use write() to add text and newLine() to add line breaks.
Handle IOException when working with file operations.