Tuesday, March 26, 2013

Redirecting output from standard output to text file, Java

There are times when you need to redirect all your output to a text file. It is very easy with command line execution by using  '>' output. However in case you want to do it programatically there is very easy way.

Following are the steps to follow:
Add following code block in starting of main function of your application (assuming you want to redirect all of your output to a text file in case not add the code at point from where you want your output to redirect to text file).
1. Create new file where you want your output to store, say out.txt here
File file = new File("out.txt");
2.  Now get output stream of this file. Using this stream, output will be sent to out.txt
FileOutputStream fileOutputStream = new FileOutputStream(file);
PrintStream printStream = new PrintStream(fileOutputStream);
3. And the last step is to update the output stream of system to our file stream instead of default console stream.
Now all is done and all of your console output will be redirected to the out.txt file. In case you want to revert the output to default console you can do by:

No comments:

Post a Comment