您可以避免使用JSAP库解析参数时出现问题。看看它有多简单:
import java.io.File;
import java.util.regex.Pattern;
import com.martiansoftware.jsap.FlaggedOption;
import com.martiansoftware.jsap.JSAP;
import com.martiansoftware.jsap.JSAPException;
import com.martiansoftware.jsap.JSAPResult;
import com.martiansoftware.jsap.stringparsers.FileStringParser;
public class Oblig4 {
private Pattern fileNamesPattern = Pattern
.compile("^[a-zA-Z0-9]{1,40}\\.txt$");
private JSAP jsap = new JSAP();
public static void main(String[] args) throws JSAPException {
Oblig4 oblig4 = new Oblig4();
oblig4.init();
JSAPResult config = oblig4.jsap.parse(args);
if (!config.success()) {
System.err.println();
System.err.println("Usage: ");
System.err.println("java -jar jar_file_name.jar "
+ oblig4.jsap.getUsage());
System.err.println(oblig4.jsap.getHelp());
System.err.println();
return;
}
File firstFile = config.getFile("firstFile");
File secondFile = config.getFile("secondFile");
if (!oblig4.fileNamesIsValid(firstFile, secondFile)) {
System.out.println("File names is not valid. See pattern "
+ oblig4.fileNamesPattern.pattern());
}
Menu menu = new Menu();
menu.doSomething(firstFile, secondFile);
}
private void init() throws JSAPException {
FileStringParser fileStringParser = FileStringParser.getParser();
fileStringParser.setMustBeDirectory(false);
fileStringParser.setMustBeFile(true);
fileStringParser.setMustExist(false);
FlaggedOption firstInputFile = new FlaggedOption("firstFile")
.setStringParser(fileStringParser).setRequired(true)
.setShortFlag('f');
firstInputFile.setHelp("First text file");
jsap.registerParameter(firstInputFile);
FlaggedOption secondInputFile = new FlaggedOption("secondFile")
.setStringParser(fileStringParser).setRequired(true)
.setShortFlag('s');
secondInputFile.setHelp("Second text file");
jsap.registerParameter(secondInputFile);
}
private boolean fileNamesIsValid(File... files) {
for (File file : files) {
if (!fileNamesPattern.matcher(file.getName()).find()) {
return false;
}
}
return true;
}
}
class Menu {
public void doSomething(File firstFile, File secondFile) {
}
}
如果没有参数或参数无效,用户将看到:
Usage:
java -jar jar_file_name.jar -f <firstFile> -s <secondFile>
-f <firstFile>
First text file
-s <secondFile>
Second text file