mactro mactro - 1 year ago 60
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();

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();

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

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 Source

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


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", " ");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download