FlashTek FlashTek - 21 days ago 8
Bash Question

Java Runtime exec() not working

I try to execute a shell command via

java
like this

if (Program.isPlatformLinux())
{
exec = "/bin/bash -c xdg-open \"" + file.getAbsolutePath() + "\"";
exec2 = "xdg-open \"" + file.getAbsolutePath() + "\"";
System.out.println(exec);
}
else
{
//other code
}
Runtime.getRuntime().exec(exec);
Runtime.getRuntime().exec(exec2);


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
xdg-open
-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
in
even the entire path is set in quotation marks?

Answer
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;
    System.out.println(exec);
}

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()) {
    Desktop.open("/path/to/file.txt");
}

Update

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