《Thinking in java》 中看的一个例子:
//: MakeDirectories.java
// Demonstrates the use of the File class to
// create directories and manipulate files.
import java.io.*;
public class MakeDirectories {
private final static String usage =
"Usage:MakeDirectories path1 ...\n" +
"Creates each path\n" +
"Usage:MakeDirectories -d path1 ...\n" +
"Deletes each path\n" +
"Usage:MakeDirectories -r path1 path2\n" +
"Renames from path1 to path2\n";
private static void usage() {
System.err.println(usage);
System.exit(1);
}
private static void fileData(File f) {
System.out.println(
"Absolute path: " + f.getAbsolutePath() +
"\n Can read: " + f.canRead() +
"\n Can write: " + f.canWrite() +
"\n getName: " + f.getName() +
"\n getParent: " + f.getParent() + 293
"\n getPath: " + f.getPath() +
"\n length: " + f.length() +
"\n lastModified: " + f.lastModified());
if(f.isFile())
System.out.println("it's a file");
else if(f.isDirectory())
System.out.println("it's a directory");
}
public static void main(String[] args) {
if(args.length < 1) usage();
if(args[0].equals("-r")) {
if(args.length != 3) usage();
File
old = new File(args[1]),
rname = new File(args[2]);
old.renameTo(rname);
fileData(old);
fileData(rname);
return; // Exit main
}
int count = 0;
boolean del = false;
if(args[0].equals("-d")) {
count++;
del = true;
}
for( ; count < args.length; count++) {
File f = new File(args[count]);
if(f.exists()) {
System.out.println(f + " exists");
if(del) {
System.out.println("deleting..." + f);
f.delete();
}
}
else { // Doesn't exist
if(!del) {
f.mkdirs();
System.out.println("created " + f);
}
}
fileData(f);
}
}
} ///:~
想问一下为什么程序执行的时候只打印完usage就退出了呢?是不是要用具体的文件名去替换什么呢?
求大牛指导!
------解决方案--------------------
args就是你运行程序输入的参数,对应 0 1 2 就是你输入的顺序,length=3就是需要3个参数,自习看一下main函数,可以有很多参数支持,第一个参数表示完成什么动作,后面的参数传入这个动作必要的参数。
------解决方案--------------------
如果你是命令行运行了就是 java MakeDirectories arg0 arg1 arg2
如果是通过Eclipse运行的,右键选择运行为,在右面的(x)=自变量里面,有个程序自变量,输入你的运行参数,多个参数以空格(或者换行)分开
------解决方案--------------------
private static void usage()
{
System.err.println(usage);
System.exit(1);