我想使用Process.waitFor()等到mysqldump完成其备份过程。这是我的代码。Process.waitFor()在mysql备份期间永远等待
///i use this mysql command, its working fine
String dump = "bkprefs/mysqldump "
+ "--host=localhost "
+ "--port=3306 "
+ "--user=root "
+ "--password= "
+ "--add-drop-table "
+ "--add-drop-database "
+ "--complete-insert "
+ "--extended-insert "
+ "test";
//execute the command
Process run = null;
try {
run = Runtime.getRuntime().exec(dump);
int stat = run.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}
问题是,run.waitfor()
挂起。它似乎一直在等待一些不会发生的事情。
当我将行int stat = run.waitFor()
替换为Thread.sleep(5)
时,备份工作正常。但我不能坚持这一点,因为备份时间会根据数据库的大小而有所不同,因此使用Thread.sleep
等待备份过程完成并不安全。
请帮帮我。回复非常感谢。
编辑:
我使用下面的代码消耗其输入流。
InputStream in = run.getInputStream();
FileWriter fstream = null;
try {
fstream = new FileWriter("haha.sql");
} catch (IOException ex) {
ex.printStackTrace();
}
BufferedWriter out = new BufferedWriter(fstream);
int nextChar;
StringBuffer sb = new StringBuffer();
try {
while ((nextChar = in.read()) != -1) {
out.write((char) nextChar);
//sb.append((char) nextChar);
}
out.flush();
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
我刚刚发布的代码后面的代码完全符合您的说法 – Jemp 2012-03-12 14:57:59
@Bnrdo - 您是否在使用_separate Thread_来处理这些流(详见该文章)? – jtahlborn 2012-03-12 17:25:00
不,用于处理这些流的代码实际上遵循备份代码。 – Jemp 2012-03-13 13:12:12