2

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?)

user3211306
  • 388
  • 1
  • 4
  • 12

3 Answers3

4
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

Nin
  • 375
  • 1
  • 11
1

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)

Per Lundberg
  • 3,837
  • 1
  • 36
  • 46
Ashishkumar Singh
  • 3,580
  • 1
  • 23
  • 41
  • Note that using `System.setOut()` and `System.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). – Per Lundberg Jan 03 '22 at 09:10
0

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

bhavna garg
  • 270
  • 2
  • 19