【发布时间】:2018-04-06 16:01:42
【问题描述】:
我必须从 Unix 平台上的 Java 程序执行命令。
我正在使用Runtime.getRuntime()。
但是,问题是我的命令是交互式的,并且在运行时要求某些参数。例如,命令是createUser。它要求userName 作为运行时。
bash-4.1$ createUser
Enter the UserName:
如何处理这种情况,以便在运行时从 Java 程序输入用户名?
try {
Process proc;
proc = Runtime.getRuntime().exec(cmd, envp);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
sb = null;
}
听说可以通过expect来实现。但是我如何在 Java 中做到这一点?
【问题讨论】:
-
我很确定(但不是完全确定)消耗两个输出流需要在不同的线程上完成。另请参阅When Runtime.exec() won't,了解有关正确创建和处理流程的许多好技巧。然后忽略它引用
exec并使用ProcessBuilder创建进程。还将String arg拆分为String[] args以解决包含空格字符的路径之类的问题。
标签: java runtime.exec