1 23 24 28 29 package com.sun.enterprise.util.io; 30 31 import java.io.*; 32 36 37 public class Tee extends PrintStream 38 { 39 40 42 private Tee(PrintStream ps) 43 { 44 super(ps); 45 } 46 47 48 50 public static void start(String f) throws IOException 53 { 54 oldStdout = System.out; 56 oldStderr = System.err; 57 58 logfile = new PrintStream(new BufferedOutputStream(new FileOutputStream(f))); 60 61 System.setOut(new Tee(System.out)); 63 System.setErr(new Tee(System.err)); 64 } 65 66 67 69 public static void stop() 71 { 72 System.setOut(oldStdout); 73 System.setErr(oldStderr); 74 75 try 76 { 77 logfile.close(); 78 } 79 catch (Exception e) 80 { 81 e.printStackTrace(); 82 } 83 } 84 85 86 88 public void write(int b) 90 { 91 try 92 { 93 logfile.write(b); 94 } 95 catch (Exception e) 96 { 97 e.printStackTrace(); 98 setError(); 99 } 100 super.write(b); 101 } 102 103 105 public void write(byte buf[], int off, int len) 107 { 108 try 109 { 110 logfile.write(buf, off, len); 111 } 112 catch (Exception e) 113 { 114 e.printStackTrace(); 115 setError(); 116 } 117 super.write(buf, off, len); 118 } 119 120 122 static OutputStream logfile; 123 static PrintStream oldStdout; 124 static PrintStream oldStderr; 125 126 128 public static void main(String [] args) 129 { 130 try 131 { 132 Tee.start("log.txt"); 135 136 System.out.println( 138 "Here's is some stuff to stdout."); 139 System.err.println( 140 "Here's is some stuff to stderr."); 141 System.out.println( 142 "Let's throw an exception..."); 143 new Exception ().printStackTrace(); 144 } 145 catch (Exception e) 146 { 147 e.printStackTrace(); 148 } 149 finally 150 { 151 Tee.stop(); 155 } 156 } 157 } 158 | Popular Tags |