从java运行vbs文件

我在C:/work/selenium/chrome/有一个VBS文件test.vbs,我想从我的Java程序运行它,所以我尝试了这个,但没有运气:

 public void test() throws InterruptedException { Runtime rt = Runtime.getRuntime(); try { Runtime.getRuntime().exec( "C:/work/selenium/chrome/test.vbs" ); } catch( IOException e ) { e.printStackTrace(); } } 

如果我尝试使用此方法运行某些exe文件,它运行良好,但是当我尝试运行VBS文件时,它说“不是有效的win32应用程序”。

知道如何从Java运行VBS文件吗?

vbs-Script本身不可执行,如bat,cmd或exe-Program。 你必须启动解释器(vbs.exe?)并将脚本作为参数传递:

 String script = "C:\\work\\selenium\\chrome\\test.vbs"; // search for real path: String executable = "C:\\windows\\...\\vbs.exe"; String cmdArr [] = {executable, script}; Runtime.getRuntime ().exec (cmdArr); 
 public static void main(String[] args) { try { Runtime.getRuntime().exec( "wscript D:/Send_Mail_updated.vbs" ); } catch( IOException e ) { System.out.println(e); System.exit(0); } } 

这是正常工作,其中Send_Mail_updated.vbs是我的VBS文件的名称

 Runtime.getRuntime().exec( "cscript E:/Send_Mail_updated.vbs" ) 
 try { Runtime.getRuntime().exec(new String[] { "wscript.exe", "C:\\path\\example.vbs" }); } catch (Exception ex) { ex.printStackTrace(); } 

您可以使用上面的代码来运行vbs文件。

完整的代码在这里

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; public class VBTest { public static void main(String[] args) { try { String line; OutputStream stdin = null; InputStream stderr = null; InputStream stdout = null; Process process = Runtime.getRuntime().exec( "cscript E:/Send_Mail_updated.vbs" ); stdin = process.getOutputStream (); stderr = process.getErrorStream (); stdout = process.getInputStream (); // "write" the parms into stdin line = "param1" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param2" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); line = "param3" + "\n"; stdin.write(line.getBytes() ); stdin.flush(); stdin.close(); // clean up if any output in stdout BufferedReader brCleanUp = new BufferedReader (new InputStreamReader (stdout)); while ((line = brCleanUp.readLine ()) != null) { System.out.println ("[Stdout] " + line); } brCleanUp.close(); // clean up if any output in stderr brCleanUp = new BufferedReader (new InputStreamReader (stderr)); while ((line = brCleanUp.readLine ()) != null) { System.out.println ("[Stderr] " + line); } brCleanUp.close(); } catch( IOException e ) { System.out.println(e); //System.exit(0); } } }