简体   繁体   中英

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? Or -HI Moon.jpg would flip the image Horizontally and Invert it? I have some methods written and they work when I run the program normally.

http://commons.apache.org/cli/

This should help. and here's how to use it: 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. 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).

您可能需要针对每种目的编写不同的方法,并根据命令输入设置if / else条件。

why not read the arguments passed and read subsequent value to do the required stuff ie,

java yourprogram -a1 something -a2 somethingelse

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
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM