It is useful to redirect standard java output to a file. However, if you are wondering why your stacktrace from e.printStackTrace() is not being redirected to a file then read on…
Say you have a program called RedirectExample.java. To redirect the output to a text file do
java RedirectExample > output.txt
However, if your code in RedirectExample.java throws an exception which you want to print via e.printStackTrace(), you wont be able to see that in output.txt. The reason is that e.printStackTrace() writes to the error stream (System.err) and the statement above does redirects only the output stream (System.out) to output.txt and not the error stream.
To redirect error stream use the following command
java RedirectExample > output.txt 2>&1
This redirects the error stream(2) to outputstream(1), which in turn is redirected to the text file.
Here’s RedirectExample.Java
public class RedirectExample {
public static void main(String[] args) {
System.out.println("From System Out");
try {
String a = null;
a.toString();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks for the information. I still can’t picture your explanation very clearly but have a rough idea of what you are trying to explain and it works. I needed this because my compilation in the DOS window was creating 100 errors and I wanted to know what was creating it. But the problem was all the earlier errors were being pushed off the capacity of the screen and I couldn’t see what they were to fix them.