Search code examples
javaprocessbuild-processruntime.exec

Using Java's exec command when you don't know if there's be spaces


I'm fighting the spaces bug in Java's Runtime exec method. Here's what's unique about this problem: the command I'm trying to execute is an incoming string and may or may not have spaces and is not necessarily in any specific format. Either way, I need to execute it. If there are no spaces, I'm good; if there are spaces, I'm not so good.

How do I account for both circumstances?

Bonus info at no extra charge: One of the big issues appears to be that I'm trying to call an executable in c:\program files\blablabla... and exec appears to split on the space after 'c:\program'. I'm sure other issues would come up for the parameters, too.

Here's a more specific example of the kinds of strings I might get. That should clear up some of the confusion:

  • c:\someApp\someapp.exe
  • c:\someApp\someapp.exe -someParam=foo
  • c:\program files\someapp\someapp.exe
  • c:\program files\someapp\someapp.exe -someParam=bar

The first one works fine because it has no spaces. The second is even okay because it splits on the space and uses the first as a command and second as a parameter. The third and fourth examples split on the first space, use 'C:\program' and the command, 'files...' and (in the case of the fourth string) '-someParam=bar' as parameters.


Solution

  • Okay, I got something working by doing something like this. Please tell me if there's a problem with this approach:

    
    try{
        String[] command = {"cmd", "/c", getMySuperAwesomeString()};
        Runtime.getRuntime().exec(command);
    }catch(IOExecption ioe){
        System.err.println("I'm borken");
    }
    
    

    On a related note, should I use ProcessBuilder instead?