gpt4 book ai didi

Java 运行时 exec() 不工作

转载 作者:行者123 更新时间:2023-11-30 08:31:37 25 4
gpt4 key购买 nike

我尝试像这样通过 java 执行 shell 命令

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 命令,但没有任何变化。

这里有什么问题,我该如何解决?

编辑:调用的输出如下所示:

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

但这对我来说似乎很奇怪 - 为什么 in 之前的命令 seperatet 甚至整个路径都用引号引起来?

最佳答案

请注意,您不需要xdg-open 来执行此操作。您可以使用与 java 平台无关的 Desktop应用程序接口(interface):

if(Desktop.isDesktopSupported()) {
Desktop.open("/path/to/file.txt");
}

更新

如果标准方法仍然存在问题,您可以将参数作为数组传递,因为 Runtime.exec 不调用 shell,因此不支持或不允许引用或转义:

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

Runtime.getRuntime().exec(new String[]{program, file.getAbsolutePath()});

关于Java 运行时 exec() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com