11

I'm trying to redirect the java compiler output to a file. I thought it's supposed to be:

javac file.java > log.txt

or something. Instead, I see all the output on the terminal and nothing in log.txt!

Also, if I want to log errors too, do I do

javac file.java 2>&1 > log.txt

?

jcee14
  • 908
  • 3
  • 15
  • 28

2 Answers2

14
javac file.java 2> log.txt

The reason is that you have two output file descriptors instead of one. The usual one is stdout, which you can redirect with > and it's supposed to be used for resulting output. The second one, stderr, is meant for human readable output like warnings, errors, current status etc., this one is redirected with 2>.

Your second line, using 2>&1, redirects stderr to stdout and finally stdout into log.txt.

Julien Oster
  • 2,256
  • 16
  • 19
  • I see redirecting stderr gives me the output that I want. Why is everything logged in stderr and nothing in stdout? Also, could you tell me why javac file.java 2>&1 > log.txt doesn't work? – jcee14 Nov 25 '08 at 15:48
  • The redirections are handled left-to-right. The 2>&1 sends stderr to the place where stdout is currently going - the terminal. Then the >log.txt sends stdout to log.txt, leaving stderr writing to the original stdout. If you wrote >log.txt 2>&1, then all output would go to the file. – Jonathan Leffler Nov 25 '08 at 15:53
  • You get bonus points if you knew that this works too: >log.txt javac 2>&1 file.java – Jonathan Leffler Nov 25 '08 at 15:55
  • 1
    The "philosophy" of stdout vs. stderr is that "cmd >foo.txt" should write something to the terminal if something goes wrong. javac follows this rule because all of its output is "something going wrong". – Darron Nov 25 '08 at 16:10
7

Have you tried

javac -Xstdout log.txt file.java

This will send compiler errors to a log file instead of stderr.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880