Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 322
Stealth Rabbi Avatar asked Aug 31 '26 10:08

Stealth Rabbi


1 Answers

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.

like image 92
Sebastian Brudzinski Avatar answered Sep 02 '26 05:09

Sebastian Brudzinski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!