Search code examples
javacommand-lineexecution

Run cmd-line in java fails


I am facing the following problem:

I am writing a java-application in Eclipse. Inside my application I want to start a cmd command:

C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect -h

The command 'connect -h' is a an enterprise internal application which works fine. If I would use a comand line a would have to chance my current directory like that:

cd C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/

and afterwards I would just type connect -h This works great. But I am not really shure how to execute this command within a java application.

Here they tell me how to run a cmd inside a java application: How to use "cd" command using Java runtime?

But if I do that:

Runtime.getRuntime().exec("'C:/Users/User1/Content-Integration Testing Framework/JDBC Connector/bin/connect' -h");

Eclipse tells me:

java.io.IOException: Cannot run program "'C:/Users/User1/Content-Integration": CreateProcess error=2, Das System kann die angegebene Datei nicht finden
    at java.lang.ProcessBuilder.start(Unknown Source)

It cuts my command at "Content-Integration".

can someone help me please?


Solution

  • You should use the version of exec() that takes multiple args via a String array.

    Runtime.exec(String s) will split your string using a tokenizer (this is why quoting the string won't work, and why you see the behaviour you do). If you resolve the executable and arguments yourself, and pass each as an array element in the above e.g.

    String[] args = new String[]{"executable", "arg1", "arg2"};
    Runtime.getRuntime().exec(args); // don't forget to collect stdout/err etc.
    

    then you will bypass Runtime.exec(String s)'s splitting behaviour.