Possible Duplicate:
BufferedReader.readLine() do not read and hang the system(wait)
尝试导入 MYSQL 数据库,但在 BufferedReader.readLine() 方法中遇到问题,它使系统等待某些内容。 代码在一段时间后导入数据库备份,但是系统总是运行并且readLine方法不允许系统前进,并且在这段代码中输出了。 1 2 3 4 4a 并且系统开始等待某些事情。 任何解决方案 提前致谢
public static boolean restoreDB(String dbName, String dbUserName, String dbPassword, String source) {
String[] executeCmd = new String[]{"C:\\Program Files\\MySQL\\MySQL Server 5.5\\bin\\mysql", "--user=" + dbUserName, "--password=" + dbPassword, "-e", "source \"D:/khokher/medmax.sql\""};
System.out.println("1 Processing Start");
Process runtimeProcess = null;
try {
String line = "";
System.out.println("2");
runtimeProcess = new ProcessBuilder(executeCmd).start();
System.out.println("3");
InputStream istrm = runtimeProcess.getInputStream();
InputStreamReader istrmrdr = new InputStreamReader(istrm);
BufferedReader buffrdr = new BufferedReader(istrmrdr);
System.out.println("4");
String data;
String st;
System.out.println("4a");
while (!(st=buffrdr.readLine()).isEmpty()) { // actual problem is in readLine Method it block system
System.out.println("5 in loop");
}
int ev = 0 ;
System.out.println("7 .waitFor()");
if (runtimeProcess.waitFor() != 0) {
ev = runtimeProcess.exitValue();
System.out.println("8 process exitValue()");
}else{
System.out.println("9 Backup restored successfully");
return true;
}
} catch(InterruptedException e){
e.printStackTrace();
System.out.println("10");
Thread.currentThread().interrupt();
return false;
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("11");
Thread.currentThread().interrupt();
return false;
} finally {
System.out.println("processing stoped");
}
return false;
}
最佳答案
buffrdr.readLine()
EOF 时返回 null
while (!(st=buffrdr.readLine()).isEmpty())
将抛出 NPE
如果你想在第一个空行之后停止阅读,你必须这样做:
while ((( st = buffrdr.readLine()) != null) && ( ! st.trim().isEmpty()))
如果没有抛出异常,程序永远不会停止,因为进程runtimeProcess
永远不会终止,也永远不会输出空行。
您应该读取runtimeProcess
的错误流,因为它可能会使流饱和,从而挂起进程(如EJP所示)。
关于java - BufferedReader.readLine()不读取并挂起系统,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13339630/