Java Beanshell scripting with args[] to the the program?

*爱你&永不变心* 提交于 2019-12-09 20:39:50

问题


The Beanshell documentation implies that you can run a script using this format on the command line:

java bsh.Interpreter script.bsh [args]

The only problem with this is that I cannot get it to work. I know how to call other scripts with args from a Beanshell script but I cannot get the initial script to take args. Help?

For example, a beanshell script like this one, wont parse the args:

import java.util.*;
for (int i=0; i < args.length; i++) {
  System.out.println("Arg: " + args[i]);
}

Also, this doesn't work either:

import bsh.Interpreter;
for( i : bsh.args )
System.out.println( i );

回答1:


The command-line arguments are available under bsh.args, not args. So if you change all instances of args in your code with bsh.args, you should be good to go. Reference: Special Variables and Values.


This worked for me:

for (arg : bsh.args)
    print(arg);

Example:

$ bsh foo.bsh 1 2 3
1
2
3



回答2:


Thanks to Chris Jester-Young I wrote a solution for this using Beanshell:

import java.util.*;
//debug();
argsList  = new ArrayList();
optsList = new HashMap();
specialOpts = new ArrayList();
int count = 0; // count the number of program args
for (int i=0; i < bsh.args.length ; i++) {
  switch (bsh.args[i].charAt(0)) {
    case '-':
        if (bsh.args[i].charAt(1) == '-') {
          int len = 0;
          String argstring = bsh.args[i].toString();
          len = argstring.length();
          System.out.println("Add special option " + 
                              argstring.substring(2, len) );
          specialOpts.add(argstring.substring(2, len));
      } else if (bsh.args[i].charAt(1) != '-' && bsh.args[i].length() > 2 ) {
            System.out.println("Found extended option: " + bsh.args[i] +
                                " with parameter " + bsh.args[i+1] );
          optsList.put(bsh.args[i], bsh.args[i+1]);
          i= i+1;
      } else if (bsh.args[i].charAt(1) != '-' && bsh.args[i].length() == 2 ) {
          System.out.println("Found regular option: " + bsh.args[i].charAt(1) + 
                             " with value " + bsh.args[i+1] );
          optsList.put(bsh.args[i], bsh.args[i+1]);
          i= i+1;
      } else if (bsh.args[i].length() <= 1) {
            System.out.println("Improperly formed arg found: " + bsh.args[i] );
        }
    break;
    default:
      System.out.println("Add arg to argument list: " + bsh.args[i] );
      argsList.add(bsh.args[i]);
    break;
  }
}


来源:https://stackoverflow.com/questions/7356979/java-beanshell-scripting-with-args-to-the-the-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!