We got a question today about how the output of a Java program running in DrJava‘s Interactions pane could be redirected into a file, just like it could be done in a Unix or DOS shell:
java Motion > motion.dat
The Interactions pane supports a simulated java
command, but this is merely for convenience. java Motion
actually translates to Motion.main(String[] {})
, which is a bit unsightly. The Interactions pane is not a Unix or DOS shell, and therefore doesn’t support input/output redirection, nor does the java
command support any of the command line options.
However, there is still a way to do input/output redirection in the Interactions pane. Here are instructions on how to redirect the System.out
stream:
- Compile your program (e.g. Motion.java).
- In the Interactions pane, import the classes from the
java.io
package:
import java.io.*
- Store the old
System.out
stream in a variable:
PrintStream oldOut = System.out
- Create a new
PrintStream
that writes to a file:
PrintStream newOut = new PrintStream(new FileStream("motion.dat"))
- Set the new stream as
System.out
:
System.setOut(newOut)
- Now run your program (but not using the “Run” toolbar button or menu item):
java Motion
- Your program will run, but all output from System.out is written to
the motion.dat file. - To get the original behavior of
System.out
back, set the old stream again:
System.setOut(oldOut)
Perhaps we could support >
and <
to do this kind of setup automatically (although only when the java
or applet
commands are used, to avoid ambiguity). There is a feature request for that already: 1506832: Interactions commands.