Java 从 Windows 使用 ProcessBuilder 执行命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21231560/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute a command using ProcessBuilder from windows
提问by Bibin
I am getting the following error when i try to execute the below line from my java program on windows machine.
当我尝试从 Windows 机器上的 java 程序执行以下行时,出现以下错误。
Could you please let me know the detailed steps to make that work?
你能告诉我使这项工作的详细步骤吗?
final Process exec = new ProcessBuilder("bash", "-c", query).start();
error : java.io.IOException: Cannot run program "bash": CreateProcess error=2, The system cannot find the file specified
错误:java.io.IOException:无法运行程序“bash”:CreateProcess 错误=2,系统找不到指定的文件
回答by Franky
Windows has no bash, so you have to use "CMD" (command). "bash" is being used for unix-systems.
Windows 没有 bash,因此您必须使用“CMD”(命令)。“bash”用于 unix 系统。
This should work on Windows :
这应该适用于 Windows:
final Process exec = new ProcessBuilder("CMD", "/C", query).start();
if you want a nice example on how to use the ProcessBuilder in Windows : External programs using Java ProcessBuilder class
如果你想要一个关于如何在 Windows 中使用 ProcessBuilder 的好例子:使用 Java ProcessBuilder 类的外部程序
回答by taymedee
If you just execute the bash command, you need the bash library for java.
如果只是执行 bash 命令,则需要 java 的 bash 库。
回答by Nitish
final Process exec = new ProcessBuilder("bash", "-c", query).start();
As the error indicates, there is no executable program bash, typically bash in installed on Unix systems at location /bin/bash, so you must provide the path to your program. Even relative paths work. This command below will work on Unix like OS with bash installed.
如错误所示,没有可执行程序 bash,通常 bash 安装在 Unix 系统上的 /bin/bash 位置,因此您必须提供程序的路径。即使是相对路径也能工作。下面的这个命令将在安装了 bash 的类似 Unix 的操作系统上工作。
final Process exec = new ProcessBuilder("/bin/bash", "-c", query).start();