Java - Standard Input/Output/Error Streams


Typically, a keyboard is a standard input device, and a console is a standard output and a standard error device.

System class declares three public static variables, one for each device: standard input, output, and error as follows:

public class System {
        public static PrintStream out; // the standard output
        public static InputStream in;  // the standard input
        public static PrintStream err; // the standard error

        // More code for the System class goes here

You can use the System.out and System.err object references wherever you can use an OutputStream object.

You can use the object wherever you can use an InputStream object.


System class has three static setter methods, setOut(), setIn(), and setErr(), to replace these three standard devices with your own devices.

To redirect all standard output to a file, call setOut() method by passing a PrintStream object that represents your file.

The following code shows how to redirect Standard Outputs to a File.



public class Main {
  public static void main(String[] args) throws Exception {
    // Create a PrintStream for file stdout.txt
    File outFile = new File("stdout.txt");
    PrintStream ps = new PrintStream(new FileOutputStream(outFile));

    // Print a message on console
    System.out.println("Messages will be redirected to "
        + outFile.getAbsolutePath());// w  w  w .j  a va 2 s  . c  om

    // Set the standard out to the file

    // The following messages will be sent to the stdout.txt file
    System.out.println("Hello world!");
    System.out.println("Java I/O is cool!");


Related Topics