📘 Writer
Overview
Writer
is an abstract class injava.io
for writing character data.- It’s the counterpart to
OutputStream
, but designed for writing text (characters and strings) rather than raw bytes.
🔽 Common Subclasses of Writer
Subclass | Description |
---|---|
BufferedWriter | Adds buffering for efficient writing of characters, arrays, and strings. |
OutputStreamWriter | Bridges character streams to byte streams using a specified charset. |
FileWriter | Convenience subclass of OutputStreamWriter to write to files (uses default charset). |
CharArrayWriter | Writes to an in-memory character array, similar to StringBuilder . |
StringWriter | Writes to an internal StringBuffer . |
PipedWriter | Used with PipedReader for inter-thread communication. |
PrintWriter | Writes formatted representations of objects (like System.out ) and supports print() and println() . |
FilterWriter | Abstract class for decorating other writer streams. |
✅ Quick Examples
1. BufferedWriter
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("Hello Buffered Writer");
writer.newLine();
writer.close();
2. OutputStreamWriter
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream("output.txt"), "UTF-8");
writer.write("Text with UTF-8 encoding");
writer.close();
3. FileWriter
FileWriter writer = new FileWriter("file.txt");
writer.write("Hello FileWriter");
writer.close();
4. StringWriter
StringWriter sw = new StringWriter();
sw.write("Hello StringWriter");
System.out.println(sw.toString());
5. PrintWriter
PrintWriter writer = new PrintWriter("log.txt");
writer.println("Log entry: " + new Date());
writer.close();
6. CharArrayWriter
CharArrayWriter caw = new CharArrayWriter();
caw.write("Hello in memory");
System.out.println(caw.toString());
caw.close();
🧵 Summary Table
Writer Subclass | Purpose |
---|---|
BufferedWriter | Efficient character output |
OutputStreamWriter | Converts characters to bytes (with charset) |
FileWriter | Writes characters to a file |
CharArrayWriter | Writes to in-memory character array |
StringWriter | Writes to string buffer (in-memory) |
PipedWriter | Sends characters to another thread |
PrintWriter | Provides formatted output, like System.out |
FilterWriter | Base for decorators |