我的Eclipse版本是Photon,docker版本是18.06.0-ce-mac70。
我想在 Eclipse 上发出 shell 脚本命令时执行 Docker 命令。
但是当我使用 shell 脚本时,
ls
命令运行良好,但不是 docker + command
错误堆栈跟踪:
`Exception in thread "main" java.io.IOException: Cannot run program
"docker": error=2, No such file or directory
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1128)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1071)
at java.base/java.lang.Runtime.exec(Runtime.java:635)
at java.base/java.lang.Runtime.exec(Runtime.java:459)
at java.base/java.lang.Runtime.exec(Runtime.java:356)
at dbUpdate.ShellCommander.shellCmd1(ShellCommander.java:36)
at dbUpdate.ShellCommander.main(ShellCommander.java:29)
Caused by: java.io.IOException: error=2, No such file or directory
at java.base/java.lang.ProcessImpl.forkAndExec(Native Method)
at java.base/java.lang.ProcessImpl.<init>(ProcessImpl.java:339)
at java.base/java.lang.ProcessImpl.start(ProcessImpl.java:270)
at java.base/java.lang.ProcessBuilder.start(ProcessBuilder.java:1107)
... 6 more
代码:
`package dbUpdate;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Scanner;`
public class ShellCommander {
static Scanner sc = new Scanner(System.in);
static String carSSID;
static String target;
static String IPAddress;
public static void main(String[] args) throws Exception {
String command = "docker ps";
shellCmd1(command);
}
public static void shellCmd1(String command) throws Exception {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(command);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
}
}
Java 不会在您的
PATH
中搜索命令。在我的 Mac 上,docker
位于 /usr/local/bin
;我也更喜欢 ProcessBuilder
而不是 Runtime.exec
。喜欢
public static void main(String[] args) throws Exception {
String command = "/usr/local/bin/docker ps";
shellCmd1(command);
}
public static void shellCmd1(String command) throws Exception {
ProcessBuilder pb = new ProcessBuilder(command.split("\\s+"));
pb.inheritIO();
Process p = pb.start();
p.waitFor();
}