Java I/O How to - Create print stream for error logger and log to a file








Question

We would like to know how to create print stream for error logger and log to a file.

Answer

/*from w  w w  .  j a va 2s . com*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Main {
  public static void main(String[] argv) throws Exception {
    try {
    } catch (Exception e) {
      e.printStackTrace(getErrorLoggerPrintStream());
    }

  }

  public static PrintStream getErrorLoggerPrintStream() {
    try {
      PrintStream s = new PrintStream(new FileOutputStream(new File("c:\\log.txt"), true));
      return s;
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    return null;
  }
}