2011-09-09 42 views
2

Beanshell文檔意味着您可以使用命令行格式運行腳本:使用args []將Java Beanshell腳本編寫到程序中?

java bsh.Interpreter script.bsh [args] 

與此唯一的問題是,我不能讓它開始工作。我知道如何使用來自Beanshell腳本的參數調用其他腳本,但我無法獲取初始腳本來引用參數。幫幫我?

例如,像這樣的一個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); 

回答

3

的命令行參數下可用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 
+0

你知道如何將bsh.args轉儲到屏幕? – djangofan

+0

工作。謝謝。 – djangofan

0

感謝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; 
    } 
}