How To Write Console Output To Text File In Java

java.lang.System out and err object are used to write text data to standard output stream and standard error stream. The default output stream is command line console. But System class also provides method for you to redirect the standard output stream to other destination 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 provide 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 is 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.");

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 exist. ");
            System.out.println("Program exist. ");

            // 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 execute above code, you can see two files out.txt and err.txt are generated under current java class execution folder as below.

READ :   Find Minimum Value In Java Array Example

redirect standard output error stream to file stream example

 

(Visited 849 times, 12 visits today)

Leave a Reply

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.