Log File using system.out

Log File using system.out

If you want your System.out.print() output to be logged in the file rather than console, then that could also be possible by little trick.

OOP_SystemOutPrintln

Before we start,

System.out.print()
 :: System - Java Main Class
 :: out - Instance of PrintStream
 :: print() - A public Method


To achieve this we need to change the property of out using System-class.

System.setOut(PrintStream p);

PrintStream : The PrintStream class provides methods to write data to another stream. The PrintStream class automatically flushes the data so there is no need to call flush() method. Moreover, its methods don’t throw IOException.

Example:

package com.helical;

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

public class SystemOutINFile {
    public static void main(String arr[]) throws FileNotFoundException
    {
        // Creating a log file object
        PrintStream printObject = new PrintStream(new File("log.txt"));

        // Storing current System.out in PrintStream before assigning some new value
        PrintStream console = System.out;

        // Assign printObject to output stream
        System.setOut(printObject);
        System.out.println("Whatever will be here in this function, it will go to text file");

       // Reassign the value for output stream
       System.setOut(console);
       System.out.println("console output");
    }
}


Hurray , That’s it….

Thanks for your time , Have a good Day 🙂

Pushpraj Kumar(Helical IT Solutions)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s