mactro mactro - 3 months ago 11
Java Question

ProcessBuilder with dynamic path (possibly with spaces)

I'm trying to run an external executable from my Java app. It resides in a package of that app, but the path to that app may vary, and may contain spaces. I have tried:

String broker = MqttServerInterface.class.getResource("broker/mosquitto.exe").getPath();

System.out.println(broker);
ProcessBuilder pb = new ProcessBuilder(broker,"-p",port);

server = pb.start();


which works fine on paths without spaces. However, when there are spaces, it gives CreateProcess error=267, the directory name is invalid.

I have rewrote the code, according to suggestions here: ProcessBuilder cannot run bat file with spaces in path:

String brokerDir = MqttServerInterface.class.getResource("broker").getPath();
System.out.println(brokerDir);

ProcessBuilder pb = new ProcessBuilder("mosquitto.exe","-p",port);
pb.directory(new File(brokerDir));
pb.redirectError();

server = pb.start();


but now, I still get error 267 with spaces in the path and error 2 (the system cannot find the file specified) without. What is a proper approach to run an executable from Java?

Answer

As you posted in a comment, the result of System.out.println(broker); displays the following:

/N:/dropbox/Dropbox/projects/robot%202.0/prophio%203/prophio3/build/classes/com‌​/trobot/prophio3/broker/mosquitto.exe

This looks like a URL-encoded URI, which is not a file path, as indicated by the occurrences of %20 in it. One way to fix this is to replace them with actual spaces, for instance like this:

broker = broker.replace("%20", " ");