Java-重定义标准输出和错误

时间:2023-03-10 04:29:17
Java-重定义标准输出和错误

刚接触到错误日志的时候觉得很神奇,今天学习了一番后用代码写了出来。

 package com.tj;

 import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream; public class TeeStream extends PrintStream {
PrintStream out; public TeeStream(PrintStream out1, PrintStream out2) {
super(out1);
this.out = out2;
} public void write(byte buf[], int off, int len) {
try {
super.write(buf, off, len);
out.write(buf, off, len);
} catch (Exception e) {
}
} public void flush() {
super.flush();
out.flush();
} public static void main(String[] args) {
try {
//Tee 标准输出
PrintStream out = new PrintStream(new FileOutputStream("E:" + File.separator + "out.log"));
PrintStream tee = new TeeStream(System.out, out); System.setOut(out); //Tee 标准错误
PrintStream err = new PrintStream(new FileOutputStream("E:" + File.separator + "err.log"));
tee = new TeeStream(System.err, err); System.setErr(tee);
} catch (FileNotFoundException e) {
e.printStackTrace();
} System.out.println("welcome");
System.err.println("error");
}
}