【问题标题】:Java Beanshell scripting with args[] to the the program?使用 args[] 为程序编写 Java Beanshell 脚本?
【发布时间】:2011-09-09 13:29:15
【问题描述】:

Beanshell 文档暗示您可以在命令行上使用这种格式运行脚本:

java bsh.Interpreter script.bsh [args]

唯一的问题是我无法让它工作。我知道如何使用 Beanshell 脚本中的 args 调用其他脚本,但我无法获取初始脚本来获取 args。帮忙?

例如,像这样的 beanshell 脚本,不会解析 args:

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

另外,这也不起作用:

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

【问题讨论】:

    标签: java arguments command-line-arguments beanshell args


    【解决方案1】:

    命令行参数在bsh.args 下可用,而不是args。因此,如果您使用bsh.args 更改代码中的所有args 实例,那么您应该很高兴。参考:Special Variables and Values


    这对我有用:

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

    例子:

    $ bsh foo.bsh 1 2 3
    1
    2
    3
    

    【讨论】:

    • 你知道如何将 bsh.args 转储到屏幕上吗?
    【解决方案2】:

    感谢 Chris Jester-Young 我使用 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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-29
      • 1970-01-01
      • 2017-10-26
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多