【发布时间】:2010-07-13 19:27:48
【问题描述】:
我正在尝试使用 ProcessBuilder 使用 Java 执行外部程序,但它需要用户输入。
更具体地说,程序是PGSQL (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();
}
非常感谢。
【问题讨论】:
标签: java