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.

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

Related posts:

  1. How Java Class files are different ?
  2. How to remove java older versions?
  3. Enhance your windows console
  4. Decompile java code with Cavaj
  5. Java decompilers

8 Comments »

  1. How to use this class? example?

    Comment by max — January 12, 2009 @ 1:07 pm

  2. just copy the source code, compile it and run. Please use editors like Eclipse to run it if you dont have any java knowledge or google for how to run a java program. Thanks.

    Comment by 0xff — January 12, 2009 @ 2:14 pm

  3. i am getting the result in the txt file as

    Redirecting output & exceptions to file
    java.lang.Exception: Test Exception
    at HtmlParseDemo.main(HtmlParseDemo.java:23)

    although my console consists of the results due to parsing an html page…

    Comment by suchetana basu — August 20, 2010 @ 11:24 am

  4. Thanks for the great example! This was exactly what I was looking for…

    Comment by Michael — September 17, 2010 @ 9:09 pm

  5. Dear respected Sir/Madam,

    I’ve tried using the example, thanks, it worked but can’t I view the “out.txt” file?

    Comment by Roshidah — November 3, 2010 @ 4:57 am

  6. Unable to run this program. Package is out of bounds . Help out.

    Comment by bella — June 2, 2011 @ 9:20 am

  7. Hello,

    Just add the code in the main class
    , just after the declaration of main method
    every line of your original code within the “try” block.

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

    // Here all your original code

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

    }

    Thank you very much, this code helped me a lot.

    Comment by Mari — June 3, 2011 @ 11:41 pm

  8. I have done as commented by Mari. I am getting reuired output in out.txt file.All is Ok except that I want to view the same output in console also, that is output in both Console and out.txt file. But I am getting no output printed in console.

    Comment by Rituparna — December 12, 2011 @ 9:06 am

RSS feed for comments on this post. TrackBack URL

Leave a comment