How to redirect console output to file using Java?

Java ConsoleIn Java printing the program output to console for debugging purposes and sometimes for understanding the program flow is very common. Sometimes programmers feel comfortable if they are able to redirect the run-time exceptions and SOPs (System.out.println) to a file for future reference. Today I am going to write about redirecting console outputs and run-time exceptions to a file. One can always argue that we can use logging frameworks like log4j, java util logging by writing custom OutputStream class and using SOPs (System.out.println) is a bad practice. I too agree with that but this is just trick for beginners to understand the basics of java and one should always avoid using SOPs while writing applications.


package com.redirect;

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

public class RedirectIO
{

	public static void main(String[] args)
	{
		PrintStream orgStream 	= null;
		PrintStream fileStream 	= null;
		try
		{
			// Saving the orginal stream
			orgStream = System.out;
			fileStream = new PrintStream(new FileOutputStream("out.txt",true));
			// Redirecting console output to file
			System.setOut(fileStream);
			// Redirecting runtime exceptions to file
			System.setErr(fileStream);
			throw new Exception("Test Exception");

		}
		catch (FileNotFoundException fnfEx)
		{
			System.out.println("Error in IO Redirection");
			fnfEx.printStackTrace();
		}
		catch (Exception ex)
		{
			//Gets printed in the file
			System.out.println("Redirecting output & exceptions to file");
			ex.printStackTrace();
		}
		finally
		{
			//Restoring back to console
			System.setOut(orgStream);
			//Gets printed in the console
			System.out.println("Redirecting file output back to console");

		}

	}
}

The above code sets the output stream of System class by creating an instance of PrintStream class with FileOutputStream as argument. This will redirect any console output using SOPs (System.out.println) to the file specified in the FileOutputStream. To redirect the runtime exceptions we need to use System.setErr. To restore the output back to cosole we are saving the stream before try to change it. In the above program I have intentionally thrown some exception to show and ensure that all runtime exceptions are captured and logged. Please do comment for any clarifications.

Popularity: 6% [?]

Share or Bookmark:
  • Sphinn
  • del.icio.us
  • Mixx
  • Google
  • BlinkList
  • Furl
  • StumbleUpon
  • TwitThis
  • YahooMyWeb

May be you like to read this

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>