Java.Streams.What is the difference between the PrintWriter class and the PrintStream?

🆚 PrintWriter vs PrintStream

FeaturePrintWriterPrintStream
Packagejava.iojava.io
ExtendsWriter (character-based)OutputStream (byte-based)
Works withCharacter streamsByte streams
Encoding-aware✅ Yes (especially with OutputStreamWriter)❌ No — uses platform default charset
Methodsprint(), 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 forText-based files, writers, UnicodeConsole output, logging, binary files
Example outputEncoded 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, like System.out.
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.