我想用Java使用ProcessBuilder执行一个外部程序,但它需要来自用户的输入。使用ProcessBuilder执行外部程序并提供输入
更具体地说,该程序是psql(Postgres SQL),当它执行时,程序会提示用户输入密码。绕过这个的唯一方法是将文件保存在包含密码的用户主目录中,我试图避免这种情况,所以我想从Java执行程序并使用进程的输出流发送密码。
当程序不期望任何用户输入时,代码工作正常,但是当我从用户主目录中删除密码文件时,程序挂起。我看到它正在执行,但没有任何反应。如果我调试它,它会到达一段时间,然后什么都不会发生,直到我杀死进程。
这是代码,任何帮助将不胜感激。
@Test
public void testSQLExecution() throws Exception {
String path = "C:/tmp";
List<String> commandList = new ArrayList<String>();
commandList.add("psql");
commandList.add("-f");
commandList.add("test.sql");
commandList.add("-h");
commandList.add(HOST);
commandList.add("-p");
commandList.add(PORT);
commandList.add("-U");
commandList.add(DATABASE);
commandList.add(SCHEMA);
ProcessBuilder processBuilder = new ProcessBuilder(commandList);
processBuilder.directory(new File(path));
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
String line;
BufferedReader input = new BufferedReader(new InputStreamReader(p
.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p
.getOutputStream()));
out.write("password");
out.newLine();
out.flush();
out.close();
// When this line is reached, the execution halts.
while (input.ready() && (line = input.readLine()) != null) {
System.out.println(line);
}
if (p.waitFor() != 0) {
Assert.fail("The process did not run succesfully.");
}
input.close();
}
非常感谢。
看到这里http://stackoverflow.com/questions/2969766/process-requires-redirected-input – Mike 2012-03-05 03:06:40