Java - How to use PrintStream/OutputStream to print to the Command Line
Solution 1
output = new PrintStream(System.out);
or actually,
output = System.out;
Similarly, you can do the same with System.err
... So why don't we just simply use System.out and System.err directly? sout + tab is quite fast to type in IntelliJ
Solution 2
System.out
or System.error
are already PrintStream
and we can use them to print the output to command line without creating a new PrintStream
object that you are doing.
Advantage of using this printStream is that you can use System.setOut()
or System.setErr()
to set the printSteam of your choice
PrintStream output = new PrintStream("./temp.txt");
System.setOut(output);
Above will override the default Printstream of printing to command line and now calling System.out.println()
will print everything in given file(temp.txt)
Related videos on Youtube
user3211306
Updated on June 04, 2022Comments
-
user3211306 almost 2 years
I know we can use PrintStream to print lines to a given file:
PrintStream output; output = new PrintStream("./temp.txt"); output .println("some output text");
However, can we use PrintStream to print lines to the command line?
I've looked through the Java docs and it seems PrintStream constructor can take a file path or an OutputStream (is there a OutputStream subclass that would print to command line?)
-
L.Spillner over 5 yearsSidenote: By definition
System.out
(stdout / Standard Outputstream) already is aPrintStream
.
-
-
Per Lundberg over 2 yearsNote that using
System.setOut()
andSystem.setErr()
replaces the standard output or standard error stream for the whole process. For a small, minimal console application this might be fine. For larger systems, complex unit/integration tests, etc., this can have severe consequences (if e.g. different parts of the system modifies these streams from multiple threads simultaneously).