FlashTek FlashTek - 1 year ago 107
Bash Question

Java Runtime exec() not working

I try to execute a shell command via

like this

if (Program.isPlatformLinux())
exec = "/bin/bash -c xdg-open \"" + file.getAbsolutePath() + "\"";
exec2 = "xdg-open \"" + file.getAbsolutePath() + "\"";
//other code

but nothing happens at all. When I execute this code it prints
/bin/bash -c xdg-open "/home/user/Desktop/file.txt"
in the console, but does not open the file. I have also tried to call the bash first and then the
-command, but there is not change.

What's the problem here and how can I solve this?

EDIT: The output of the calling looks like this:

xdg-open "/home/user/Desktop/files/einf in a- und b/allg fil/ref.txt"
xdg-open: unexpected argument 'in'

But this seeems very strange to me - why is the command seperatet before the
even the entire path is set in quotation marks?

Answer Source
xdg-open "/home/user/Desktop/files/einf in a- und b/allg fil/ref.txt" xdg-open: unexpected argument 'in'

Unlike windows, Linux doesn't use quotes to escape spaces, it uses \.

So, your string should be

xdg-open /home/user/Desktop/files/einf\ in\ a-\ und\ b/allg\ fil/ref.txt

Which escaped becomes:

xdg-open /home/user/Desktop/files/einf\\ in\\ a-\\ und\\ b/allg\\ fil/ref.txt

Using your code:

if (Program.isPlatformLinux())
    String path = file.getAbsolutePath().replace(" ", "\\ ");
    exec = "/bin/bash -c xdg-open " + path ;
    exec2 = "xdg-open " + path;

Also, please note that you don't need xdg-open to do this. You can use the java platform-agnostic Desktop API:

if(Desktop.isDesktopSupported()) {


If the standard approach still gives issues, you can try passing the command as an array, as it automatically escapes everything:

String program;
if (Program.isPlatformLinux())
    program = "xdg-open";
} else {
    program = "something else";

Runtime.getRuntime().exec(new String[]{program, file.getAbsolutePath()});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download