Java Reference
In-Depth Information
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
}
The JVM initializes the three variables to appropriate values. 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.
Java lets you use these three objects in the
System
class in one more way. If you do not want the three objects to
represent the standard input, output, and error devices, you can supply your own devices; Java will redirect the data
flow to/from these objects to your devices.
Suppose, whenever you call the
System.out.println()
method to print a message on the console, you want to
send all messages to a file instead. You can do so very easily. After all,
System.out
is just a
PrintStream
object and you
know how to create a
PrintStream
object using a
FileOutputStream
object (refer to Listing 7-19) to write to a file. The
System
class provides 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, you need to call the
setOut()
method by
passing a
PrintStream
object that represents your file. If you want to redirect the output to a file named
stdout.txt
in
your current directory, you do so by executing the following piece of code:
// Redirect all standard ouputs to the stdout.txt file
PrintStream ps = new PrintStream(new FileOutputStream("stdout.txt"));
System.setOut(ps);
Listing 7-36 demonstrates how to redirect the standard output to a file. You may get a different output on the
console. You will see the following two messages in the
stdout.txt
file in your current working directory, after you
run this program:
Hello world!
Java I/O is cool!
You may get a different output when you run the program as it prints the path to the
stdout.txt
file using your
current working directory.
Listing 7-36.
Redirecting Standard Outputs to a File
// CustomStdOut.java
package com.jdojo.io;
import java.io.PrintStream;
import java.io.FileOutputStream;
import java.io.File;
public class CustomStdOut {
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());