[英]Control program from command line arguments
How do I pick the methods in my program to run using command line arguments? 如何选择程序中的方法以使用命令行参数运行? For example, if I want my program to process an image called Moon.jpg, how do I make it work so that -S Moon.jpg in the command line would invoke the Scale method?
例如,如果我希望我的程序处理名为Moon.jpg的图像,如何使它工作,以便命令行中的-S Moon.jpg可以调用Scale方法? Or -HI Moon.jpg would flip the image Horizontally and Invert it?
或-HI Moon.jpg会水平翻转图像并将其反转? I have some methods written and they work when I run the program normally.
我写了一些方法,当我正常运行程序时它们可以工作。
http://commons.apache.org/cli/ http://commons.apache.org/cli/
This should help. 这应该有所帮助。 and here's how to use it: http://commons.apache.org/cli/usage.html
以及使用方法: http : //commons.apache.org/cli/usage.html
You can parse arguments with a function like this: 您可以使用以下函数解析参数:
private void parseArguments(String[] args)
{
int i = 0;
String curArg;
while (i < args.length && args[i].startsWith("-"))
{
curArg = args[i++];
if ("-S".compareTo(curArg) == 0)
{
if (i < args.length)
{
String image = args[i++];
processImage()
}
else
{
// ERROR
}
}
}
}
Your main method should always have String[] args which contains arguments split on the space character. 您的main方法应始终具有String [] args,其中包含在空格字符上分割的参数。 There are also plenty of libraries you can use to parse command line arguments.
您还可以使用许多库来解析命令行参数。 This method is quite similar to what the Apaches CLI library uses (Of course there's a lot more that comes with that library but the parser uses this logic).
此方法与Apaches CLI库使用的方法非常相似(当然,该库附带了很多东西,但解析器使用此逻辑)。
您可能需要针对每种目的编写不同的方法,并根据命令输入设置if / else条件。
why not read the arguments passed and read subsequent value to do the required stuff ie, 为什么不读取传递的参数并读取后续值以执行所需的操作,即,
java yourprogram -a1 something -a2 somethingelse
java yourprogram -a1东西-a2东西
and in your program 在你的程序中
public static void main(String[] args){
for(int i=0;i<args.length;i++){
switch(args[i]){//you can use if-else to deal with string...
case "-a1":read args[i+1] to get value to do somethng
case "-a2": read args[i+1] to get value to do something else
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.