0

I have a problem with this code:

 try {            
    String cmd = "C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe -uroot -proot foo_db -rC:\\backup.sql";

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd);

 } catch(Exception e) {}

It doesn't get any error, pratically it doesn't DO anything: no backup and no execution of the cmd. Where's the problem?

It's strange, because the cmd-text is correct... i've tried to do it with 'Execute' command in windows and it works, but in java no.

Thanks in advance.

2
  • 2
    Does it throw an exception? Try adding e.printStackTrace() inside your catch clause. Commented Feb 10, 2012 at 17:33
  • uhm... yes, now it made an error: "java.io.IOException: Cannot run program "C:\Program": CreateProcess error=193, %1 isn't a Win32 valid application" Commented Feb 10, 2012 at 17:44

2 Answers 2

3

Your first problem was, as @pcalcao pointed out, that you are not reporting the exception. You really should never do this. At the very least you should do:

} catch(Exception e) {
    e.printStackTrace();
}

java.io.IOException: Cannot run program "C:\Program": CreateProcess error=193, %1 isn't a Win32 valid application

That says that you have a problem with your application path. By default, if exec() is called with a single argument, then it will break the arguments up by spaces. Since you have spaces in your path you need to pass an array of strings to exec(). Something like:

try {            
    String cmd =
        "C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysqldump.exe";
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(new String[] { cmd, "-uroot", "-proot", "foo_db",
        "-rC:\\backup.sql" });
    // wait for it to finish
    proc.waitFor();
} catch(Exception e) {
    e.printStackTrace();
}

The first argument in the string array passed to exec() is then the full path to the command -- this can have spaces. Each of the other array elements is an argument to the command.

Lastly, you will need to wait for the process to finish otherwise it will execute in the background. That's what the waitFor() does.

Sign up to request clarification or add additional context in comments.

1 Comment

Classic 'spaces in the path' problem.
0

You need to escape the whitespace with \, exec is trying to execute "C:\Program", from what you've showed in your answer to my previous comment.

NEVER leave a catch clause empty.

2 Comments

I've resolved putting \" to path, now it works. Thanks for the advices!
No problem :) The right way of thanking for a correct answer on SO is by accepting the answer ;)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.