Middle
What is the difference between the classes PrintWriter and PrintStream?
sobes.tech AI
Answer from AI
PrintWriter and PrintStream are classes for outputting data, but with different features:
- PrintStream works with byte streams (OutputStream), while PrintWriter works with character streams (Writer).
- PrintWriter supports specifying character encoding, which is important for correct text handling in different locales.
- PrintWriter has methods for automatic buffer flushing (autoFlush) when calling println, printf, and format.
- PrintStream does not support encoding directly and is outdated for text output.
Example of creating a PrintWriter with specified encoding:
PrintWriter writer = new PrintWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), true);
writer.println("Sample output with PrintWriter");
Thus, for text output, it is preferable to use PrintWriter, especially if encoding is important.