Java - Standard Input/Output/Error Streams

Introduction

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 System.in object wherever you can use an InputStream object.

Redirect

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.

Demo

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

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());//from ww w.  j  a  va 2 s .  co  m

    // Set the standard out to the file
    System.setOut(ps);

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

Result

Related Topics