Redirect Console Output
The previous article talked about console input, it is time to write something about console output.
To print something to the console window, simply write :
// console output
System.out.println("Hello !");
System.out is a system variable in Java. Looking at the documentation of java.lang.System, you will find System.out is actually a PrintStream.
A PrintStream is capable of writing output to file or console window. To redirect System.out, we just need to define a new PrintStream targeting to a text file instead of the console window.
public class MySystemOut extends java.io.PrintStream
{
private java.io.PrintStream oldOut=null;
public MySystemOut() throws Exception
{
super(new java.io.FileOutputStream("out.txt"),true);
}
}
We need to define two more methods in MySystemOut, namely startRedirect() and stopRedirect(). The method names are self explanatory.
// defined inside class MySystemOut
public void startRedirect()
{
oldOut = System.out;
System.setOut(this);
}
public void stopRedirect()
{
System.setOut(oldOut);
}
You will need a testing program which contains a main() method. It just creates a MySystemOut object and starts the redirect process.
/******************************************************************************
* File : A.java
* Author : http://java.macteki.com/
* Description :
* Main program for testing MySystemOut
* Tested with : JDK 1.6
******************************************************************************/
public class A
{
public static void main(String[] args) throws Exception
{
MySystemOut out=new MySystemOut();
System.out.println("Going to redirect System.out...");
out.startRedirect();
for (int i=0;i<10;i++)
System.out.println("this should be in out.txt:"+i);
out.stopRedirect();
System.out.println("Console output restored !");
for (int i=0;i<10;i++)
System.out.println("this should be on console screen:"+i);
}
}
MySystemOut.java
/******************************************************************************
* File : MySystemOut.java
* Author : http://java.macteki.com/
* Description :
* A class to redirect System.out
* Tested with : JDK 1.6
******************************************************************************/
public class MySystemOut extends java.io.PrintStream
{
private java.io.PrintStream oldOut=null;
public MySystemOut() throws Exception
{
super(new java.io.FileOutputStream("out.txt"),true);
}
public void startRedirect()
{
oldOut = System.out;
System.setOut(this);
}
public void stopRedirect()
{
System.setOut(oldOut);
}
}
Compilation and Testing
To compile, you need both A.java and MySystemOut.java in the same folder, issue :javac *.javaTo run, just type :
java A
An output file "out.txt" will be generated in the same folder.
Thanks for reading. Comments are welcome.
No comments:
Post a Comment