🆚 PrintWriter
vs PrintStream
Feature | PrintWriter | PrintStream |
---|---|---|
Package | java.io | java.io |
Extends | Writer (character-based) | OutputStream (byte-based) |
Works with | Character streams | Byte streams |
Encoding-aware | ✅ Yes (especially with OutputStreamWriter ) | ❌ No — uses platform default charset |
Methods | print() , println() , printf() , write() | print() , println() , printf() , write() |
Autoflush | ✅ Optional (with constructor flag) | ✅ Optional (with constructor flag) |
Can suppress IOExceptions? | ✅ Yes (can check checkError() ) | ✅ Yes (can check checkError() ) |
Better for | Text-based files, writers, Unicode | Console output, logging, binary files |
Example output | Encoded characters (using specified charset) | Raw bytes with system encoding |
📘 Example: PrintWriter
with UTF-8
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("out.txt"), "UTF-8"
)
);
pw.println("Привет, мир!"); // UTF-8 encoded
pw.close();
📘 Example: PrintStream
(like System.out
)
PrintStream ps = new PrintStream("out.txt");
ps.println("Hello, world!"); // Uses default encoding (e.g., Windows-1251)
ps.close();
🔥 Summary
- Use
PrintWriter
when working with characters, especially if you care about encoding (e.g., UTF-8). - Use
PrintStream
for legacy code, quick logging, or binary output, likeSystem.out
.