How to redirect System.out output to a file, instead of Console

You can read about standard input ans standard output stream details here. As known System.out represents Standard output stream, and anything written to standard output stream, gets displayed on console screen. How ever it is possible to redirect output of System.out to any OutputStream, like FileOutputStream, or to Network. Below is an example, on how to redirect the content written to System.out to a file name abcd.txt.

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

public class SystemIORedirectDemo {
public static void main(String[] args) {
	try{
	FileOutputStream fos = new FileOutputStream("abcd.txt");
	PrintStream ps = new PrintStream(fos);
	System.setOut(ps);
	
	System.out.println("Hello, How are you");
	System.out.println("Note that this content is saved to abcd.txt file");
	}
	catch(IOException ioe)
	{
		System.out.println("IOException occurred:"+ioe.getMessage());
	}
}
}

By default, System.in reads each character from Keyboard. Below is an example on how to redirect System.in. Similarly it is also possible to redirect System.err

import java.io.FileInputStream;
import java.io.IOException;

public class SystemIORedirect1Demo {
public static void main(String[] args) throws IOException{
	FileInputStream fis = new FileInputStream("abcd.txt");
	
	System.setIn(fis);
	
	int i = 0;
	while(i != -1)
	{
	i = System.in.read();//reads each character from the file abcd.txt
	System.out.print((char)i);//prints the character read, above
	}
}
}

You may also like to read:

java standard input and output