【问题标题】:Executing command line using "Runtime.getRuntime().exec()"使用“Runtime.getRuntime().exec()”执行命令行
【发布时间】:2017-06-25 19:16:21
【问题描述】:

我在从 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

【问题讨论】:

  • Windows 没有echo
  • 在 cmd 中,确实如此......但这不是这里的问题。
  • 这是一个内置的cmd 命令。不是外部程序。在 *NIX 上,它是一个独立的程序。
  • 例如,当我在 java 类中使用命令帮助时,它确实可以工作......那么为什么其他命令行不能在 cmd 上完美运行
  • @Joe17 如果您有能力,请随时为他人回答您自己的问题。

标签: java eclipse command-line


【解决方案1】:

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

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

【讨论】:

    最近更新 更多