How To Write Console Output To Text File In Java

The java.lang.System‘s out and err objects are used to write text data to the standard output stream and standard error stream. The default output stream is the command-line console. But the java.lang.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.

  1. The java.lang.System class provides the below methods to set standard output stream to custom stream.
  2. setOut(PrintStream ps): Set standard data output to a specified print stream such as a file stream.
  3. setErr(PrintStream ps):  Set standard error output to a specified print stream such as a file stream.
  4. setIn(InputStream is): Set standard input stream to a custom input stream.

2. Redirect Java Out Error Stream Examples.

  1. Below are the steps of redirecting the output stream to the file stream.
  2. Create a file output print stream.
    PrintStream fileOut = new PrintStream("./out.txt");
  3. Call System.setOut method to set above PrintStream as the new standard output stream.
    System.setOut(fileOut);
  4. 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.

  1. 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;
        }
    
    }
  2. After executing the above code, you can see two files out.txt and err.txt are generated under the current java class execution folder.
  3. Below is another method to write user input in the command line console to a 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;
        }
    
    }
    

4. Why My Java Code Can Not Write Console Output To A Local Log Text File.

4.1 Question.

  1. I am new to java programming. And my java program generates a lot of log output text on the console screen using the method system.out.println() (2022/05/24).
  2. I want to save the above log text output to a log file instead of printing them on the console.
  3. Below is an example java source code, but it does not work as expected when I run it. Can anyone give me some suggestions? Thanks a lot.
    try {
            
          // Create an InputStreamReader object to read the system standard input.	
          InputStreamReader isr = new InputStreamReader(System.in)
    
          // Create an instance of the BufferedReader object based on the above InputStreamReader object.
          BufferedReader brIn = new BufferedReader(isr);
    
          // Create a FileWriter object to write text data to the log file.
          FileWriter fw = new FileWriter("log.txt")
    
          // Create an instance of the PrintWriter class to print text to FileWriter object.
          PrintWriter pw = new PrintWriter(fw);
    
    
          // Read one line of text from the console input.
          String lineText = brIn.readLine();
    
          // Print one line of text to the log.txt file.
          pw.println(lineText);
    
          // Close the PrintWriter object.
          pw.close();
    
    }catch(IOException e1) {
          System.out.println(e1.getMessage());
    }

4.2 Answer1.

  1. If you want to print the system standard output from the default console screen to a special file, you should change your java source code as below.
    // Create an instance of the PrintWriter class to print text to FileWriter object.
    PrintWriter pw = new PrintWriter(fw);
    
    // Set the PrintWriter object to the system standard output.
    System.setOut(pw);
  2. The code System.setOut(pw) is very important, it will direct all your system.out.printiln() method printed text to the PrintWriter object. Then all those texts will be written to the PrintWriter wrapped text file.
  3. The above code will print text to the custom text file, but it will truncate the file when you print new text to the file.
  4. If you want to append the new text to the existing text file, you can set the append parameter to true to achieve this like the below source code.
    bool append = true;
    
    bool autoFlush = true;
    
    // Create the FileOutputStream object in append mode.
    FileOutputStream fos = new FileOutputStream("log.txt", append)
    
    // Create the PrintStream object with auto flush, then when the system.out.println() method is called the text will be flushed to the log.txt file immediately.
    PrintStream ps = new PrintStream(fos, autoFlush);
    
    // Set the PrintStream object to the syste.output.
    System.setOut(ps);

1 thought on “How To Write Console Output To Text File In Java”

  1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

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