使用args 将Java Beanshell脚本编写到程序中?
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 );
命令行参数在bsh.args
下bsh.args
,而不是args
。 因此,如果您使用bsh.args
更改代码中的所有args
实例,那么您应该很高兴。 参考: 特殊变量和值 。
这对我有用:
for (arg : bsh.args) print(arg);
例:
$ bsh foo.bsh 1 2 3 1 2 3
感谢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; } }