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?)
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
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)
The PrintStream class provides methods to write data to another stream. To print to command line you can use System.out
as out is an object of PrintStream
class.
import java.io.*;
class PrintStreamTest{
public static void main(String args[])throws Exception{
PrintStream pout=new PrintStream(System.out);
pout.println(1900);
pout.println("Hello Java");
pout.println("Welcome to Java");
pout.close();
}
}
This will give output on command line as:
1900
Hello Java
Welcome to Java
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.