How To Write Console Output To Text File In Java

java.lang.System out and err objects are used to write text data to the standard output stream and standard error stream. The default output stream is command-line console. But System class also provides a method for you to redirect the standard output stream to other destinations such as file stream. With this, you can log text data to a log file in your java program.

1. Redirect Java System Output Stream Methods.

java.lang.System class provides the below methods to set standard output stream to custom stream.

  1. setOut(PrintStream ps): Set standard data output to a specified print stream such as a file stream.
  2. setErr(PrintStream ps):  Set standard error output to a specified print stream such as a file stream.
  3. setIn(InputStream is): Set standard input stream to a custom input stream.

2. Redirect Java Out Error Stream Examples.

Below are the steps of redirect output stream to file stream.

  1. Create a file output print stream.
    PrintStream fileOut = new PrintStream("./out.txt");
  2. Call System.setOut method to set above PrintStream as the new standard output stream.
    System.setOut(fileOut);
  3. Call System.out.println to write text data to the file.
    System.out.println("Email " + line + " is valid. Please input another one.");

3. Write Console Output To Text File In Java Examples.

Below is the full example source code.

package com.dev2qa.java.basic;

import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;

public class OutputStreamRedirect {

    public static void main(String[] args) {

        try
        {
            // Save original out stream.
            PrintStream originalOut = System.out;
            // Save original err stream.
            PrintStream originalErr = System.err;

            // Create a new file output stream.
            PrintStream fileOut = new PrintStream("./out.txt");
            // Create a new file error stream. 
            PrintStream fileErr = new PrintStream("./err.txt");

            // Redirect standard out to file.
            System.setOut(fileOut);
            // Redirect standard err to file.
            System.setErr(fileErr);

            // Wrapped Scanner to get user input.
            Scanner scanner = new Scanner(System.in);

            // Print data in command console.
            originalOut.println("Please input your email. ");

            // Read string line.
            String line = scanner.nextLine();

            while(true)
            {
                // If user input 'quit' then break the loop.
                if("quit".equalsIgnoreCase(line))
                {
                    break;
                }

                if(!isValidEmail(line))
                {
                    // If user input is not a valid email then write log data to ./err.txt file and console.
                    originalErr.println("Email " + line + " is not a valid email. Please input again.");
                    System.err.println("Email " + line + " is not a valid email. ");
                }else
                {
                    // If user input a valid email then write the email to ./out.txt and console.
                    originalOut.println("Email " + line + " is valid. Please input another one.");
                    System.out.println("Email " + line + " is valid. Please input another one.");
                }
                // Get next user input line text.
                line = scanner.nextLine();
            }

            originalOut.println("Program exit. ");
            System.out.println("Program exit. ");

            // Do not forget set original output and error stream back again.
            System.setOut(originalOut);
            System.setErr(originalErr);

        }catch(FileNotFoundException ex)
        {
            ex.printStackTrace();
        }
    }

    /* Check whether the string is an email address or not. */
    private static boolean isValidEmail(String email)
    {
        boolean ret = true;

        if(email==null || email.trim().length()==0)
        {
            ret = false;
        }else
        {
            int index = email.indexOf("@");
            if(index == -1)
            {
                ret = false;
            }
        }

        return ret;
    }

}

After executing the above code, you can see two files out.txt and err.txt are generated under the current java class execution folder as below.

redirect-standard-output-error-stream-to-file-stream-example

Below is another method to write user input in command line console to text file in java.

package com.dev2qa.java.basic;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class OutputStreamRedirect {

    public static void main(String[] args) {
        
        
        try {
            
              // Create an instance of InputStreamReader class, it is used to read user input from command line console.
              InputStreamReader isr = new InputStreamReader(System.in);
              
              // Create an instance of OutputStreamWriter class, it is used to write text to command line console.
              OutputStreamWriter osw = new OutputStreamWriter(System.out);
              
              
              // Create a BufferedReader object and use this object to connect to the system.in(command line console) to get user input text.
              BufferedReader br = new BufferedReader(isr);
              
              // Create a BufferedWriter object to write text to system.out.
              BufferedWriter bw = new BufferedWriter(osw);
              
              bw.write("Please input a valid email address.\r\n");
              bw.flush();

              // Get user input text line from the command line console.
              String line = br.readLine();

              if(isValidEmail(line))
              {
            	  // If user input valid email address.
            	  String text = line + " is a valid email address.\r\n";
            	  
            	  // Print the text to system.out command line console.
            	  bw.write(text);
            	  bw.flush();
                  
            	  // Print the user input email address to a text file.
                  FileWriter fw = new FileWriter("out.txt");
                  PrintWriter pw = new PrintWriter(fw);
                  pw.println(text);
                  // Do not forget close the above writers to close the file pointer.
                  pw.close();
              }else {
            	  
            	  // If user input invalid email address.  
            	  String text = line + " is not a valid email address.\r\n";
            	  
            	  // Print the error text to system.out command line console.
            	  bw.write(text);
            	  bw.flush();
            	  
            	  // Print the error text to an err.txt file.
            	  FileWriter fw = new FileWriter("err.txt");
                  PrintWriter pw = new PrintWriter(fw);
                  pw.println(text);
                  // Close the above writer object to close the file.
                  pw.close();
              }
           }catch(IOException e1) {
                System.out.println("Error during reading/writing");
           }
    }
        

        
    
    /* Check whether the string is an email address or not. */
    private static boolean isValidEmail(String email)
    {
        boolean ret = true;
        
        if(email==null || email.trim().length()==0)
        {
            ret = false;
        }else
        {
            int index = email.indexOf("@");
            if(index == -1)
            {
                ret = false;
            }
        }
        
        return ret;
    }

}
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Freddie Pope
Freddie Pope

I have an existing java class which contains a lot of System.out.println() method to print text to the standard output console. But when the java class execute, I need the log text write to a file instead of writing to java standard output console. And I searched out this article. But it is difficult to update my old java class because there are too many System.out.println() lines, so I google out below method can also achieve this. In a terminal and run the command java Yout-Class-Name >> out.txt. Then it will print all the output text generated by the System.out.println() method to the text file.

1
0
Would love your thoughts, please comment.x
()
x