[英]How to create a Jar file with execution options?
How can I create a jar file with execution options, for example, the idea is execute the command: 如何创建具有执行选项的jar文件,例如,执行命令是:
java -jar MyProgram.jar -M someFile.txt
or 要么
java -jar MyProgram.jar -cp someFile.txt
So the -M option defines a particular method to process the file someFile.txt and with -cp defines another behavior for the code. 因此,-M选项定义了一种处理文件someFile.txt的特定方法,而-cp选项定义了代码的另一种行为。
With this in mine, how can I get this result from my code, is there something I need to write in the Main class, or how can I define such behavior? 有了这个,我如何从代码中获得结果,是否需要在Main类中编写某些内容,或者如何定义这种行为?
I think you probably need to check the Apache Commons-CLI, it allows you to do the things you describe above, also I give an example how it works, it give the way to specify a message for the usage of the arguments: 我认为您可能需要检查Apache Commons-CLI,它可以使您执行上面描述的操作,还给出一个示例,说明其工作原理,并提供了一种方法来指定使用参数的消息:
https://commons.apache.org/proper/commons-cli/introduction.html https://commons.apache.org/proper/commons-cli/introduction.html
Options options = new Options();
options.addOption( "M", false,"Merge files request.")
.addOption("CP", false,"Copy files from file.");
CommandLineParser parser = new DefaultParser();
try {
CommandLine cmd = parser.parse(options, args);
if (!cmd.hasOption("M")) {
throw new IllegalArgumentException("Must specify an input file.");
}
// Do something
if (!cmd.hasOption("CP")) {
throw new IllegalArgumentException("Must specify an input file.");
}
// Do something
catch (Exception e) {
System.out.println(e.getMEssage());
}
take a look at this example . 看 这个例子 。
basically the args
in your main method 基本上是您主要方法中的args
public static void main(String[] args) { ... }
args = the arg ument s you put after java -jar MyJar.jar
for example -cp someFile.txt
as a String[]: {"-cp", "someFile.txt"}
ARGS =所述ARG ument 是你后把java -jar MyJar.jar
例如-cp someFile.txt
作为字符串[]: {"-cp", "someFile.txt"}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.