如何用Java中的参数运行VBS函数并将结果赋值给variables
我有这个macros的macros:
Function Calculate_Something(StartDate As Date, EndDate As Date) As Double //some math is here, not important Calculate_Something = Result End Function
而且我想把我的date传递给这个macros,在我的Java程序中执行它,最后得到返回值并将其赋值给我的Java值。
我用这个函数创build了VBS脚本,并尝试在Java中像这样执行它:
String[] parms = {"wscript", "calc.vbs", "2017-02-06 09:38:36", "2017-02-06 12:47:41"}; Runtime.getRuntime().exec(parms);
但它没有工作。 你知道我怎么能这样做?
您将需要使用cscript.exe
而不是wscript.exe
,它们都是相同的主机,但是一个是为GUIdevise的,而另一个是为命令行devise的。
修改VBScript函数以输出Result
到屏幕(执行的命令输出stream),然后使用从调用Runtime.getRuntime().exec(parms);
派生的Process
对象来检索它Runtime.getRuntime().exec(parms);
。
有一个叫做getInputStream()
的Process
对象的方法,它允许你访问和读取脚本输出返回的值。
try { String[] parms = {"cscript", "calc.vbs", "2017-02-06 09:38:36", "2017-02-06 12:47:41"}; Process p = Runtime.getRuntime().exec(parms); // Get Input Stream from the Process BufferedReader is = new BufferedReader(new InputStreamReader(p.getInputStream())); // Do something with stream, read etc. String line; while ((line = is.readLine()) != null) System.out.println(line); } catch (Exception ex) { ex.printStackTrace(); }
有用的链接
- vbscript输出到控制台
- 什么是InputStream和输出stream? 为什么我们使用它们,我们什么时候使用它们?
- 了解getInputStream和getOutputStream