12

Hello I try to run the following cmd code in eclipse:

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

In clear it looks like this:

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

But I get following error message:

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)
....

When I try to use the code in the cmd box, Its working fine. My code:

    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 Answer 1

19

Add "cmd.exe /c" at the beginning of your command string, that should do the trick.

The /c parameter will make the cmd finish and return it to the Java process.
Without it, the process will hang.

2
  • When I did this I got nothing in return. May 24, 2016 at 13:19
  • 3
    If you're using ProcessBuilder::start instead of Runtime::exec, you need to pass the strings "cmd", "/c" and "dir" separately to the constructor.
    – Zsolt Z.
    Jan 29, 2019 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.