Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Directing System.out.println() output to a file instead to console in Java.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 175
    Comment on it

    Directing System.out.println() output to a file instead to console in Java.

    The internal working of System.out.println():

    System: java.lang package contains the class System with it's definition.

    out: out is a public and static variable of System class. out is an instance of PrintStream class. Printstream class provides methods to write data to another stream. out can be referred as "standard" output stream.

    println: println is a public method of Printstream class which is called by out to print the string to the console.

    System.out.println() generally prints messages to the console but it can be used to print messages to other sources also, the only change required is to reassign the standard output by using System.setOut method of System class.

    Syntax of System.setOut method:

    System.setOut(PrintStream p);

    //Program to redirect output of System.out.println() to a text file

    import java.io.*;
    
    public class SystemFact
    {
        public static void main(String a[]) throws FileNotFoundException
        {
            PrintStream o = new PrintStream(new File("A.txt"));  //File object created
    
            PrintStream console = System.out;    // store current standard output
    
            System.setOut(o);    // o is assigned to output stream
    
            System.out.println("This will be written to the text file");
    
            System.setOut(console);  //reassign the standard output
    
            System.out.println("This will be written on the console!");
        }
    }

    Expalnation:

    First System.out.println writes output to file A.txt and second System.out.println writes output to the console. This is done by changing the output stream using setout method of System class.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: