e054. redirecting standard output, and error.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 45 行

TXT
45
字号
This example replaces standard output and error with a print stream that copies its output to both the console and to a file. 
    // All writes to this print stream are copied to two print streams
    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();
        }
    }

Here's an example that uses the class: 
    
    try {
        // Tee standard output
        PrintStream out = new PrintStream(new FileOutputStream("out.log"));
        PrintStream tee = new TeeStream(System.out, out);
    
        System.setOut(tee);
    
        // Tee standard error
        PrintStream err = new PrintStream(new FileOutputStream("err.log"));
        tee = new TeeStream(System.err, err);
    
        System.setErr(tee);
    } catch (FileNotFoundException e) {
    }
    
    // Write to standard output and error and the log files
    System.out.println("welcome");
    System.err.println("error");

 Related Examples 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?