Site icon

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

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”)

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

1. String written to error console
2. Another String written to error console
Exit mobile version