如何使用exec()方法在java代码中运行Windows控制台应用程序?

时间:2011-07-12 11:19:38

标签: java runtime.exec

如何使用Runtime.getRuntime()。exec()?

我试试:

try {
    String[] callAndArgs = {"path\\program.exe","arg1","arg2","arg3"}
    System.out.println("before");
    Process p = Runtime.getRuntime().exec(callAndArgs)
    System.out.println("in");
    p.waitFor();
    System.out.println("after");
} catch (IOException e) {
            System.out.println("catch io: " + e.getMessage());
        } catch (InterruptedException ie) {
            System.out.println("catch ie: " + ie.getMessage());
        }

程序不起作用。输出:

before
in
after

HM?帮助; p

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

也许这也有帮助(http://ubuntuforums.org/showthread.php?t=681779),

import java.lang.* ;

 public class MyJavaClass
 {
 public void runCmd(String[] args)
 {
 String cmd = "/home_dir/./my_shell_script.sh" ;
 Runtime run = Runtime.getRuntime() ;
 Process pr = run.exec(cmd) ;
 pr.waitFor() ;
 BufferedReader buf = new BufferedReader( new InputStreamReader( pr.getInputStream() ) ) ;

 while ( ( String line ; line = buf.readLine() ) != null ) 
 {
 System.out.println(line) ;
 }

 }

 }