How to change standard output and standard error device to file in java

By default when we print anything using system.out.println(” Hello World”) and system.err.println(“Hello World”). It will redirect the output to standard output device (CONSOLE) and and standard error device (CONSOLE).We can change this behaviour.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class ChangeStandardOutputAndError {

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

File fileError = new File("STDError.log");
FileOutputStream fosError = new FileOutputStream(fileError);
PrintStream psError = new PrintStream(fosError);
System.setErr(psError);

System.err.println("Hello STDError Device");

File fileOut = new File("STDOutPut.log");
FileOutputStream fosOut = new FileOutputStream(fileOut);
PrintStream psOut = new PrintStream(fosOut);
System.setOut(psOut);

System.out.println("Hello STDOutput Device");

}

}

Now we can see System.out.println(); and System.err.println() will write the message in the corresponding files.

This entry was posted in Java. Bookmark the permalink.

Leave a comment