Java.Streams.What subclasses of the Writer class do you know, what are they for?

📘 Writer Overview

  • Writer is an abstract class in java.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

SubclassDescription
BufferedWriterAdds buffering for efficient writing of characters, arrays, and strings.
OutputStreamWriterBridges character streams to byte streams using a specified charset.
FileWriterConvenience subclass of OutputStreamWriter to write to files (uses default charset).
CharArrayWriterWrites to an in-memory character array, similar to StringBuilder.
StringWriterWrites to an internal StringBuffer.
PipedWriterUsed with PipedReader for inter-thread communication.
PrintWriterWrites formatted representations of objects (like System.out) and supports print() and println().
FilterWriterAbstract 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 SubclassPurpose
BufferedWriterEfficient character output
OutputStreamWriterConverts characters to bytes (with charset)
FileWriterWrites characters to a file
CharArrayWriterWrites to in-memory character array
StringWriterWrites to string buffer (in-memory)
PipedWriterSends characters to another thread
PrintWriterProvides formatted output, like System.out
FilterWriterBase for decorators
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.