0

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?

Selphiron
  • 897
  • 1
  • 12
  • 30

1 Answers1

2

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.

f1sh
  • 11,489
  • 3
  • 25
  • 51
  • Thx for your answer. It worked but what surprises me is that when I open cmd.exe and type md C:\blabla the new directory is created (Windows 7 64 bit). Anyways thank you :) – Selphiron Nov 05 '14 at 16:25
  • Just giving a command to ``cmd.exe`` as parameter doesn't mean that cmd takes it and executes it. Check ``cmd.exe /?`` to check what the parameters do. – f1sh Nov 05 '14 at 19:22