/* Utility class duplicates System.out and System.err to a file. Useful for simple logging purposes. Usage: see main method for example usage. Build: javac DupeStream.java Alex Wong, Aug 2002 */ import java.io.*; public class DupeStream extends PrintStream { static PrintStream sysout; static PrintStream syserr; static OutputStream log=null; static boolean bothStream=true; public static void main(String argv[]) throws Exception { //invoke main method from command line with: java DupeStream if (argv.length < 1) { System.out.println("Usage: java DupeStream "); System.exit(1); } System.out.println("Line 1"); //lines 1,2,3,4 goes to console(if bothStream=true) DupeStream.start(argv[0],true,true); //Append output to logfile, display output to stdout/err as well. System.out.println("Line 2"); //lines 2,3 goes to logfile System.out.println("Line 3"); DupeStream.stop(); System.out.println("Line 4"); } public DupeStream(PrintStream ps) { //constructor super(ps); } public static void start(String outfile,boolean append,boolean both) { //Open outfile. set sysout and syserr to outfile. if both=true, write to both file & stdout/err. try { log = new PrintStream(new BufferedOutputStream(new FileOutputStream(outfile,append))); sysout = System.out; syserr = System.err; bothStream=both; System.setOut(new DupeStream(System.out)); System.setErr(new DupeStream(System.err)); } catch (Exception e) { System.out.println(e.toString()); } } public static void stop() { //reset sysout & syserr to prev stream. Close log file. if (log != null) { System.setOut(sysout); System.setErr(syserr); try { log.close(); } catch (Exception e) {} } } public void write(int b) { //intercept the write int method in OutputStream and write to logfile first. if (log != null) { try { log.write(b); } catch (Exception e) {} if (bothStream) super.write(b); } } public void write(byte buf[],int offset,int len) { //intercept the write byte buf method in OutputStream and write to logfile first. if (log != null) { try { log.write(buf,offset,len); } catch (Exception e) {} if (bothStream) super.write(buf,offset,len); } } public void write(byte buf[]) { //intercept the write byte buf method in OutputStream and write to logfile first. if (log != null) { try { log.write(buf,0,buf.length); } catch (Exception e) {} if (bothStream) super.write(buf,0,buf.length); } } }