Stealth Rabbi
Stealth Rabbi

Reputation: 10346

Runtime exec with arguments containing spaces

I have an application I'm trying to run through a Runtime.exec() call.

Since some of the arguments have spaces, how can I properly escape the arguments such that it works both in Linux and Windows? I know with Windows, you typically use double quotes around a string with spaces, while linux uses a slash.

With the spaces, I'd expect the program I'm running (Windows' xcopy for now) to return almost immediately and indicate the number of parameters is wrong. But, the waitFor() call hangs.

String[] commandArray = new String[3];
commandArray[0] = applicationPath;
commandArray[1] = someFileWhichMayHaveSpaces;
commandArray[2] = anotherFileWhichMayHaveSpaces;

Process appProcess = Runtime.getRuntime().exec(commandArray);
int returnCode = appProcess.waitFor();

Upvotes: 3

Views: 1655

Answers (3)

Sebastian Brudzinski
Sebastian Brudzinski

Reputation: 878

I've had identical issue with the application I've been developing few weeks ago. Ultimately, I gave up on using raw Runtime.exec() (pitfalls of Runtime.exec()) and decided to use Apache Commons Exec library. It helped to solve various problems out of box and random hanging during execution. Its addArguments() method takes handleQuoting parameter, so I created a simple util method that checks the OS and I request handling quoting for Windows, while for Linux I pass false. If you want some working examples, there are some tutorials on the library website. You may also take a look at my class that uses commons-exec in the Open LaTeX Studio project.

Upvotes: 4

Harry Johnston
Harry Johnston

Reputation: 36348

On Windows, if in doubt you should use one of the overloads of Runtime.exec that takes a string, rather than a string array, as the command line argument. That allows you to construct the command line string for the new process yourself, so you can ensure that the syntax is correct.

If you use the array method, Java has to convert the array into a single string. It will do so using the standard algorithm, which assumes that the target process uses the Microsoft C runtime command line parser (or a compatible one). This will usually be OK, but not always.

Upvotes: 0

Stealth Rabbi
Stealth Rabbi

Reputation: 10346

Looks like there isn't an issue at all with spaces in the args, at least testing in teh Windows environment. The issue was that xcopy was prompting /halting for a response to a question if the copy source was a file or directory. I assumed it was choking on the spaces, but apparenlty it was not. I was able to use the code I have in the question as is, and didn't have to use ProcessBuilder.

Upvotes: 0

Related Questions