Java Runtime exec() not working

拜拜、爱过 提交于 2020-01-04 09:04:18

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/40569006/java-runtime-exec-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!