Replace standard output and error with a print stream, output to both the console and to a file. : IO redirection « File « Java Tutorial






import java.io.FileOutputStream;
import java.io.PrintStream;

public class Main {
  public static void main(String[] argv) throws Exception {
    System.setOut(new LogStream(System.out, new PrintStream(new FileOutputStream("out.log"))));
    System.setErr(new LogStream(System.err, new PrintStream(new FileOutputStream("err.log"))));
    
    System.out.println("output");
    System.err.println("error");
  }
}

class LogStream extends PrintStream {
  PrintStream out;

  public LogStream(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();
  }
}








11.70.IO redirection
11.70.1.Redirect standard error
11.70.2.Redirect standard output
11.70.3.Redirecting Standard Output, and Error
11.70.4.Replace standard output and error with a print stream, output to both the console and to a file.
11.70.5.Standard Err and Output Windows
11.70.6.Redirect standard output to a file
11.70.7.Demonstrates standard I/O redirection