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?
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 pass the parameters as an array since Runtime.exec
does not invoke a shell and therefore does not support or allow quoting or escaping:
String program;
if (Program.isPlatformLinux())
{
program = "xdg-open";
} else {
program = "something else";
}
Runtime.getRuntime().exec(new String[]{program, file.getAbsolutePath()});