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
- FileOutputStream is an output stream, we can use to write data to a file.
- We can use PrintWriter to write formatted text to a file.
- Then we write the code and parse the output to a string.
- 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.
- If the operation is successful we display the success message.
- 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:
An output.txt file is created when the program is executed:
When we open the output.txt file, we can find the output of the program, we just executed.
Hope you understood the code 🙂
Any questions please feel free to drop in your comments.
You can also read:
- Sum of all numbers in a String in Java
- Shift elements of an array to right in Java
- Maximum sum of an Hourglass in a Matrix in Java
What directory does the file go to?