Write or redirect standard output error stream to a file in java

  • We write error of an application(s) to standard error stream using System.err.print*.
    • System.err.println(“1. Write error to a file”);
  • We would like to redirect the application errors to a file.
    •  e.g. System.err.println(“1. Write error to a file”) should be written to a file.
    • We would like to set output stream, so that all errors will be written to a file.
  • System class has setErr method to set the error output stream.
    • static void setErr(PrintStream err)
      Reassigns the “standard” error output stream.

Code :write or redirect output error stream to file in java

package org.learn;

import java.io.FileNotFoundException;
import java.io.PrintStream;


public class WriteConsoleErrorToFile {

    public static void main(String[] args)  throws FileNotFoundException {
        writeErrorOutputToFile();
    }

    private static void writeErrorOutputToFile() throws FileNotFoundException {

        System.err.println("1. String written to error console");
        System.err.println("2. Another String written to error console");

        PrintStream printStream = new PrintStream("ErrorOutputToFile.txt");
        System.setErr(printStream);

        System.err.println("1. Write error to a file");
        System.err.print("2. Write another error to a file");
        System.err.printf("\n3. Exceptions will be written to file as an error");
    }
}

O/P: Contents written to a file (“ErrorOutputToFile.txt”)

  • “ErrorOutputFile.txt” file will be generated in the current working directory.
  • The error contents written to a file is as follows:
  • 1. Write error to a file
    2. Write another error to a file
    3. Exceptions will be written to file as an error

O/P:  Content written to standard error stream in java

1. String written to error console
2. Another String written to error console
Scroll to Top