Runtime exec whose parameters contain spaces
I have an application that is trying to run via a Runtime.exec() call.
Since some parameters have spaces, how can I properly escape these parameters so that they are valid in both Linux and Windows? I know that in Windows you usually use double quotes around strings with spaces, while Linux uses slashes.
With spaces, I expect the program I’m running (currently xcopy for Windows) to return almost immediately with an indication of the wrong number of arguments. However, the waitFor() call hangs.
String commandArray = new String; commandArray = applicationPath; commandArray = someFileWhichMayHaveSpaces; commandArray = anotherFileWhichMayHaveSpaces; Process appProcess = Runtime.getRuntime().exec(commandArray); int returnCode = appProcess.waitFor();
had the same issue in the app I developed a few weeks ago. Eventually, I abandoned using the original
Runtime.exec() ( pitfalls of Runtime.exec() and decided to use the Apache Commons Exec library. Solves various problems such as out-of-the-box use and messy hanging when executing. Its
addArguments() method takes the
handleQuoting parameter, so I created a simple util method to check the OS and request to handle Windows references, while for Linux, I passed false. If you want some working examples, there are some tutorials on the library website. You can also take a look at my class, which is in commons-exec is used in Open LaTeX Studio. Project.