Appearance
PrintStream and PrintWriter
PrintStream
is a FilterOutputStream
that provides additional methods on top of the OutputStream
interface for writing various data types:
- Write
int
:print(int)
- Write
boolean
:print(boolean)
- Write
String
:print(String)
- Write
Object
:print(Object)
(which is equivalent toprint(object.toString())
) - ...
- A corresponding set of
println()
methods, which automatically append a newline.
The commonly used System.out.println()
actually uses PrintStream
to print various data. Here, System.out
is the default PrintStream
provided by the system, representing standard output:
java
System.out.print(12345); // Outputs 12345
System.out.print(new Object()); // Outputs something like java.lang.Object@3c7a835a
System.out.println("Hello"); // Outputs Hello and moves to a new line
System.err
is the standard error output provided by the system.
Compared to OutputStream
, PrintStream
adds a set of print()
/println()
methods that allow for easy printing of various data types. Another advantage is that it does not throw IOException
, so you don't need to catch IOException
when writing code.
PrintWriter
PrintStream
ultimately outputs byte data, while PrintWriter
extends the Writer
interface, and its print()
/println()
methods output character data. The usage of both is almost identical:
java
import java.io.*;
public class Main {
public static void main(String[] args) {
StringWriter buffer = new StringWriter();
try (PrintWriter pw = new PrintWriter(buffer)) {
pw.println("Hello");
pw.println(12345);
pw.println(true);
}
System.out.println(buffer.toString());
}
}
Summary
PrintStream
can accept various data types for output, making it convenient for printing data:System.out
is standard output.System.err
is standard error output.
PrintWriter
is output based onWriter
.