Manish,
You can create a new PrintStream that is chained to a FileOutputStream that points to your output file. You then reassign the standard System.out PrintStream to your new PrintStream using System.setOut.
I have included a sample class below that reassigns System.out to print to a file and then reassigns it back to print to the standard terminal output:
import java.io.*;
public class Reassign {
public static void main(
String args[] ) {
try {
// Optional capture of original standard out print
// stream to reset to default later if desired
PrintStream ops = System.out;
// Create new file and print steams for new standard out
FileOutputStream fs = new FileOutputStream("Test.dat");
PrintStream nps = new PrintStream(fs);
// Reassign standard out to new print stream
System.setOut(nps);
System.out.println( "Reassign to new PrintStream" );
nps.close();
// Reassign standard out to old default print stream
System.setOut(ops);
System.out.println( "Reassign to old PrintStream" );
ops.close();
}
catch (IOException e ) {
System.out.println( "Standard out could not be"
+ " reassigned");
}
}
}
Hope this helps,
Bob Kerfoot -
SCJP