How to redirect Output of a Program to a Text file in Java

In this tutorial, we will learn how to redirect or save the output of a Program to a Text file in Java. There are many ways of doing this. One method I find simple is by the use of PrintWriter class.

Explanation

  1. FileOutputStream is an output stream, we can use to write data to a file.
  2. We can use PrintWriter to write formatted text to a file.
  3. Then we write the code and parse the output to a string.
  4. When the code is executed, a new file is created and the program output is written to the file by the use of PrintWriter write method.
  5. If the operation is successful we display the success message.
  6. Else if we encounter an IO Exception we print the error message on the console.

Code to Save Output of a Program to a Text file in Java

import java.util.*;
import java.io.*;

class Output
{
  public static void main(String args[])
  {
    try
    {
      File f = new File("Output.txt");
      FileOutputStream fos = new FileOutputStream(f);
      PrintWriter pw = new PrintWriter(fos);

      int[]arr = {54,63,14,6,21,5,94,2};
      Arrays.sort(arr);
      String s = "";

      for(int i = 0; i < arr.length; i++)
      {
        s = s + arr[i] + ",";
      }
    
      pw.write(s);
      pw.flush();
      fos.close();
      pw.close();	
      System.out.println("Output Written to file");
    }
    
    catch(IOException ex)
    {
      ex.printStackTrace();
    }
    
  }
}


Output:

Save Output of a Program to a Text file in Java

An output.txt file is created when the program is executed:

Redirect Output of a Program to a Text file in Java

When we open the output.txt file, we can find the output of the program, we just executed.

output.txt

Hope you understood the code 🙂
Any questions please feel free to drop in your comments.

You can also read:

Leave a Reply

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