Java Reference
In-Depth Information
Example
Suppose a compiled Java program called Copy.class copies the contents of one fi le
into another. Rather than prompting the user to enter the names of the fi les (which
would be perfectly feasible, of course), the program may allow the user to specify
the names of the two fi les as command line parameters:
java Copy source.dat dest.dat
(Please ignore the fact that MS-DOS has a perfectly good copy command that
could do the job without the need for our Java program!)
Method main would then access the fi le names through arg[0] and arg[1] :
import java.io.*;
import java.util.*;
public class Copy
{
public static void main(String[] arg)
throws IOException
{
//First check that 2 fi le names have been
//supplied…
if (arg.length < 2)
{
System.out.println(
"You must supply TWO fi le names.");
System.out.println("Syntax:");
System.out.println(
" java Copy <source> <destination>");
return;
}
Scanner source = new Scanner(new File(arg[0]));
PrintWriter destination =
new PrintWriter(new File(arg[1]));
String input;
while (source.hasNext())
{
input = source.nextLine();
destination.println(input);
}
source.close();
destination.close();
}
}
Search WWH ::




Custom Search