Redirecting Output

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

Yes—but not with files. Input has been text from the keyboard and output has been text to the monitor.

Redirecting Output

The command line interface of most operating systems supports file redirection. This works for Windows operating systems and operating systems based on Unix, including Max OS X. A program that sends its output to the monitor can send its output to a file using output redirection. Say that you have a program named Hello.java that writes "Hello World" to the monitor. Here is how the program usually works:

C:/> java Hello
Hello World
C:/>

Without making any changes to the program and without recompiling you can do this:

C:/> java Hello > output.txt
C:/> 

This command creates the file called output.txt and fills it with the characters that otherwise would go to the monitor. You can pick any name you want for the output file (but do not pick the name of a file already in the subdirectory because the new file will replace the old file). You do not have to end the file name with .txt but doing that is a helpful reminder about what the file contains. When the program finishes, the file output.txt remains on the disk. For example:

C:/>type output.txt
Hello World
C:/> 

The TYPE command given at the command shell asks the operating system to type the file out on the monitor. It works with any text file.

QUESTION 8:

Can Notepad be used to edit output.txt?