Java Runtime exec()无法正常工作 [英] Java Runtime exec() not working
问题描述
我尝试通过 java
这样执行shell命令
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);
但是什么也没有发生.当我执行此代码时,它将在控制台中输出/bin/bash -c xdg-open"/home/user/Desktop/file.txt"
,但不会打开文件.我也尝试过先调用bash,然后再调用 xdg-open
-命令,但是没有改变.
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?
调用的输出如下所示:
xdg-open"/home/user/Desktop/files/einf in a- and b/allg fil/ref.txt"xdg-open:意外参数'in'
xdg-open "/home/user/Desktop/files/einf in a- und b/allg fil/ref.txt" xdg-open: unexpected argument 'in'
但这对我来说似乎很奇怪-为什么即使在整个路径都用引号引起来的情况下,为什么在 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?
推荐答案
请注意,您无需 xdg-open
即可执行此操作.您可以使用与Java平台无关的桌面 API:
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");
}
更新
如果标准方法仍然存在问题,则可以将参数作为数组传递,因为 Runtime.exec
不会调用外壳程序,因此不支持或不允许使用引号或转义符:
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()});
这篇关于Java Runtime exec()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!