Java BufferedWriter
📝 Java BufferedWriter
BufferedWriter is a character output stream used to write text to a file efficiently.
It buffers characters to reduce the number of write operations, improving performance, especially for large files.
Package:
java.ioSuperclass:
WriterOften used with FileWriter for writing text files.
✅ Syntax
🔹 1. Writing Text to a File
newLine()adds a platform-independent newline.Use try-with-resources to automatically close the writer.
🔹 2. Appending Data to a File
To append to an existing file, pass true as the second argument to FileWriter:
🔹 3. Writing Multiple Lines Using a Loop
Efficient for writing large amounts of data.
🔹 4. Important Methods
| Method | Description |
|---|---|
write(String s) | Writes a string to the file |
newLine() | Writes a newline character |
flush() | Forces any buffered data to be written immediately |
close() | Closes the writer and releases resources |
✅ Best Practices
Always wrap
FileWriterwithBufferedWriterfor efficiency.Use try-with-resources to automatically close the stream.
Use
flush()if you need to write buffered data immediately.
Summary
BufferedWriter= Efficient character output streamWrites lines or text to a file
Use with FileWriter for text files
Ideal for writing large files or multiple lines
