cd assignment1i.e., a command to change the current working directory to
assignment1
. The above command
actually consists of two components:
cd
-- for change directory
assignment1
--the new current working directory
lsin Unix lists the contents of the current directory (same as the
dir
command in Windows).
This command takes no arguments.
cp oldfile newfilein Unix copies
oldfile
to newfile
. This program takes 2 arguments.
Thus, we see that a program can be invoked with arguments that provide information to the program from the user. We call these command line arguments.
In order for this information to be of any value to the program, we must be able to access the command line arguments from within the program.
java Finder supermarket testfile.txt(this is an example command line for the example presented below).
We are invoking the Java interpreter, java
, passing it the name of the class whose main
is
to be executed. The actual command line arguments are supermarket
and testfile.txt
.
main
we wish to launch
main
,
just as arguments would be passed to any other function.
Thus, the signature of the main
is:
public static void main(String [] args)
args
therefore is an array of Strings containing the command line arguments in the order in which they
appear on the command line. In the example:
java Finder supermarket testfile.txtwe have:
args[0]: supermarket args[1]: testfile.txtThe
args
array is processed just like any other array pf String
.
Finder
Finder
is a program that accepts a string (the program calls it the pattern and an arbitrary
number of file names and prints out the names of all those files that contain the string.
The program accepts an arbitrary number of arguments -- the first (args[0]
is the pattern, and the rest are
the names of the files to be searched.
The program also contains the standard logic for detecting and notifying the user if there are an invalid number
of arguments, as well as logic for returning an appropriate exit status (using the method System.exit
:
0 if the pattern was found, 1 if it wasn't found in any of the files, and 2 if there were an invalid # of arguments.