Getting System Out to Write to a Particular File on System

JavaIO

This tutorial redirects the System.out to a file provided by the user.

Steps to follow –

1. Create a file myconsole.txt.
2. Create a PrintStream which uses FileOutputStream
3. Set the System Out with PrintStream object.

package com.jkoder;

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

public class RedirectSystemOutput {

	public static void main(String[] args) throws FileNotFoundException {
		System.out.println("This output can be seen at Console");

		File file = new File("myconsole.txt");
		FileOutputStream fos = new FileOutputStream(file);
		PrintStream ps = new PrintStream(fos);
		System.setOut(ps);
		System.out.println("This output goes to myconsole.txt");
	}
}