Search code examples
javaapachecmdapache-commons-exec

running simple cmd.exe commands with apache commons exec


I want to run cmd.exe commands from java (for example md C:\blabla to create a new directory C:\blabla ) My code looks like this and it runs without any errors:

import java.io.IOException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;

public class Test {

    public static void main(String[] args) throws ExecuteException, IOException {
        CommandLine cmdLine = new CommandLine("cmd.exe");
        cmdLine.addArgument("md");
        cmdLine.addArgument("C:\\blabla");
        DefaultExecutor executor = new DefaultExecutor();
        executor.execute(cmdLine);
    }
}

But if I go to C:\ there is no folder blabla as I would expect, since manually typing md C:\blabla in cmd.exe works fine. I also tried "C:\Windows\System32\cmd.exe" instead of "cmd.exe" but no use.

The output in the Console looks like this:

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users\Selphiron\workspace\Test>

Where is the mistake?


Solution

  • The mistake is the command itself. Just try what you did in the command line.

    Your code passes something like "cmd.exe md c:\blabla" to the system. That starts a new shell. Just passing a shell command to cmd.exe doesnt do the trick. Try to use

    cmd /c md c:\blabla
    

    The /c makes all the difference here.