runtime.getRuntime()。exec() - 在IDE中使用的某些命令,而不是来自可执行的.jar文件?
我将 Maven Spring Boot 项目导出为 .jar 文件,除了我的应用程序应该在终端中运行的一些命令之外,一切似乎都工作正常。
例如,“shutdown now”将运行,并关闭电脑,但“xdg-open somelink.com”不执行任何操作?
我尝试通过以下两种方式执行终端命令:
public void runInTerminal(String cmd){
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", cmd);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
也尝试过
public void commandRun(String cmd) throws IOException, InterruptedException {
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
}
感谢您的宝贵时间!
I exported my Maven Spring Boot project as a .jar file, and everything seems to be working fine, except for a few commands that my app is supposed to run in the Terminal.
For example "shutdown now" will run, and turn off the PC, but "xdg-open somelink.com" doesn't do anything?
I've tried executing the terminal commands in the following two ways:
public void runInTerminal(String cmd){
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("bash", "-c", cmd);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Success!");
System.out.println(output);
System.exit(0);
} else {
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
And also tried
public void commandRun(String cmd) throws IOException, InterruptedException {
Runtime run = Runtime.getRuntime();
Process pr = run.exec(cmd);
pr.waitFor();
}
Thank you for your time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
检查
/lib/jspawnhelper/jspawnhelper
是否启用了-X 标志
(可执行文件)。ProcessBuilder 是 Runtime.exec 的包装器,它通过操作系统本机执行命令。如果没有操作系统级别的可执行标志,您将无法执行命令。
Check that
<jre-dir>/lib/jspawnhelper/jspawnhelper
have the-X flag
(executable) enabled.ProcessBuilder
is a wrapper forRuntime.exec
who is exeucte commands nativly throu the OS. Without the executable-flag on os-level you can not execute commands.