使用“Runtime.getRuntime()。exec()”执行命令行

时间:2017-06-25 19:16:22

标签: java eclipse command-line

从Java代码执行命令行时遇到问题 这是我使用的代码,在代码下面是我得到的错误 我也尝试使用ProcessBuilder,但我遇到了同样的错误。

Ps:我在Windows上运行该程序。

public class Test {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        Process compilerProcess = Runtime.getRuntime().exec("clafer -k -m choco clafer.cfr);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(
                compilerProcess.getInputStream()));
            String s = null;
            while ((s = stdInput.readLine()) != null) {
             System.out.print(s);        }  
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // To have access to the text generated by the compiler.


}

}

错误:

java.io.IOException: Cannot run program "echo": CreateProcess error=2, the 
  specified file is not found
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at eqe.Test.main(Test.java:12)
Caused by: java.io.IOException: CreateProcess error=2, the specified file 
is not found
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 5 more

1 个答案:

答案 0 :(得分:0)

我找到了问题的解决方案。我只是将命令行放入新的String []并工作 以下是使用命令行的解决方案,允许您执行长命令行。

Process compilerProcess = Runtime.getRuntime().exec(new String[]{"clafer","-k","-m","choco","clafer.cfr" });