Java Reference
In-Depth Information
// 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!");
}
}
Messages will be redirected to C:\book\javabook\stdout.txt
Generally, you use System.out.println() calls to log debugging messages. Suppose you have been using this
statement all over your application and it is time to deploy your application to production. If you do not take out the
debugging code from your program, it will keep printing messages on the user's console. You do not have time to go
through all your code to remove the debugging code. Can you think of an easy solution? There is a simple solution to
swallow all your debugging messages. You can redirect your debugging messages to a file as you did in Listing 7-36.
Another solution is to create your own concrete component class in the OutputStream class family. Let's call the new
class DummyStandardOutput , as shown in Listing 7-37.
Listing 7-37. A Dummy Output Stream Class That Will Swallow All Written Data
// DummyStandardOutput.java
package com.jdojo.io;
import java.io.OutputStream;
import java.io.IOException;
public class DummyStandardOutput extends OutputStream {
public void write(int b) throws IOException {
// Do not do anything. Swallow whatever is written
}
}
You need to inherit the DummyStandardOutput class from the OutputStream class. The only code you have to write is to
override the write(int b) method and do not do anything in this method. Then, create a PrintStream object by wrapping
an object of the new class and set it as the standard output using the System.setOut() method shown in Listing 7-38. If you
do not want to go for a new class, you can use an anonymous class to achieve the same result, as follows:
System.setOut(new PrintStream(new OutputStream() {
public void write(int b) {
// Do nothing
}}));
Listing 7-38. Swallowing All Data Sent to the Standard Output
// SwallowOutput.java
package com.jdojo.io;
import java.io.PrintStream;
public class SwallowOutput {
 
Search WWH ::




Custom Search