By default, the standard input stream System.in is associated with the keyboard,
while the standard output stream System.out is associated with the VDU. If,
however, we wish input to come from some other source (such as a text fi le) or
we wish output to go to somewhere other than the VDU screen, then we can
redirect the input/output. This can be extremely useful when debugging a pro-
gram that requires anything more than a couple of items of data from the user.
Instead of re-entering the data each time we run the program, we simply create
a text fi le holding our items of data on separate lines (using a text editor or
wordprocessor) and then re-direct input to come from our text fi le. This can save
a great deal of time-consuming, tedious and error-prone re-entry of data when
debugging a program.
We use ' < ' to specify the new source of input and ' > ' to specify the new output
java ReadData < payroll.txt
java WriteData > results.txt
When the fi rst of these lines is executed, program 'ReadData(.class)' begins
execution as normal. However, whenever it encounters a fi le input statement
(via Scanner method next , nextLine , nextInt , etc.), it will now take as its input
the next available item of data in fi le 'payroll.txt'. Similarly, program
'WriteData(.class)' will direct the output of any print and println statements to
fi le 'results.txt'.
We can use redirection of both input and output with the same program, as the
example below shows. For example:
java ProcessData < readings.txt > results. txt
For program 'ProcessData(.class)' above, all fi le input statements will read from
fi le 'readings.txt', while all print s and println s will send output to fi le 'results.txt'.
Command Line Parameters
When entering the java command into a command window, it is possible to sup-
ply values in addition to the name of the program to be executed. These values
are called command line parameters and are values that the program may
make use of. Such values are received by method main as an array of String s. If
this argument is called arg [Singular used here, since individual elements of the
array will now be referenced], then the elements may be referred to as arg ,
arg , arg , etc.