Java.io.IOException: 无法运行程序"dir": CreateProcess错误=2,Das System

12

你好,我尝试在Eclipse中运行以下命令代码:

 "DIR \""+DEV_HOME+"\\src\"\\*.java /b /s >> \""+DEV_HOME+"\\bin\\javaFiles.txt\""

翻译后的内容:

明确来看,它是这样的:

DIR "D:\Thomas\Dokumente\Daten\workspace\WBRLight\src"\*.java /b /s >> "D:\Thomas\Dokumente\Daten\workspace\WBRLight\bin\javaFiles.txt"

但我收到了以下错误信息:

java.io.IOException: Cannot run program "dir": CreateProcess error=2, Das System kann die angegebene Datei nicht finden
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1041)
at java.lang.Runtime.exec(Runtime.java:617)
at java.lang.Runtime.exec(Runtime.java:450)
....

当我在 cmd 窗口中尝试使用这段代码时,它可以正常运行。 我的代码:

    public void run_cmdLine(String command) {
    try {
        Runtime rt = Runtime.getRuntime();
        BufferedReader input = null;
        Process pr = null;

        pr = rt.exec(command);
        input = new BufferedReader(new inputStreamReader(pr.getInputStream()));

        String line = null;

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

        int exitVal = pr.waitFor();
        System.out.println("Exited with error code " + exitVal);

    } catch (Exception e) {
        System.out.println(e.toString());
        e.printStackTrace();
    }
}
1个回答

19

在你的命令字符串开头添加 "cmd.exe /c",这应该就可以解决问题了。

/c 参数将使 cmd 完成并将其返回到 Java 进程。
没有它,进程会挂起。


当我这样做时,我没有得到任何回报。 - Martin Erlic
3
如果你正在使用ProcessBuilder :: start而不是Runtime :: exec,那么你需要将字符串“cmd”,“/ c”和“dir”分别传递给构造函数。 - Zsolt Z.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接