我想用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