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.
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"); } }
Best Open Source Business Intelligence Software Helical Insight is Here
A Business Intelligence Framework
Hurray , That’s it….
Thanks for your time , Have a good Day 🙂
Pushpraj Kumar(Helical IT Solutions)
java log file printstream setout system.out log
Subscribe
Login
0 Comments