Write or redirect console output to a file & again reset to standard output in java

  1. In java application, we write to console output using System.out.print*.
  2. We would like to redirect console output to a file. (Stream output -> File)
    • e.g. System.out.println(“1. Console output written to file”) should written to a file.
    • Stream written to console output will be redirected to a file.
  3. We will demonstrate to reset the console output (Opposite of Step 2 – Stream output -> Standard output).
    • We will redirect the stream to standard output instead of a file.
    • We will reset the standard output, so that stream output will be redirected to Standard console output.
  4. System class has setOut method to set the stream output.
    • static void setOut(PrintStream out)
      Reassigns the “standard” output stream.

1. Write console output to a file & reset back to standard output in java

package org.learn;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


public class WriteConsoleOutputToFile {

    public static void main(String[] args)  throws FileNotFoundException {
        writeConsoleOutputToFile();
    }
    private static void writeConsoleOutputToFile() throws FileNotFoundException {

        System.out.println("1. String written to console");
        System.out.println("2. Another String written to console");

        PrintStream printStream = new PrintStream("ConsoleOutputFile.txt");
        System.setOut(printStream);

        System.out.println("1. Console output written to file");
        System.out.print("2. Another console output written to file");
        System.out.printf("\n3. Write yet another string to file");

        //Redirect to console output
        PrintStream consoleStream = new PrintStream(
                                    new FileOutputStream(FileDescriptor.out));
        System.setOut(consoleStream);
        System.out.println("3. Reset to write on console output");
        System.out.println("4. Demonstration of console output");

    }
}

2. O/P: Contents written to a “ConsoleOutputFile.txt” file

  • “ConsoleOutputFile.txt” file will be generated in the current working directory.
  • The contents written to a file is as follows:
  • 1. Console output written to file
    2. Another console output written to file
    3. Write yet another string to file

3. O/P:  Content written to standard console in java

1. String written to console
2. Another String written to console
3. Reset to write on console output
4. Demonstration of console output
Scroll to Top