2011-09-12 59 views
2

我想運行mysql來執行一些來自java的文件。 輸入被從文件中讀取,並應管道輸送到mysql進程,寄託都似乎確定,但該行進程掛起在waitFor()

int exitCode = proc.waitFor(); 

永遠不會返回。

private boolean runScript(String path, String cmd, File file) throws IOException, InterruptedException { 
     Runtime rt = Runtime.getRuntime(); 
     Process proc = rt.exec(path + File.separatorChar + cmd); 
     OutputStream procOS = proc.getOutputStream(); 
     InputStream procES = proc.getErrorStream(); 
     InputStream procIS = proc.getInputStream(); 
     OutputStreamWriter procStdIn = new OutputStreamWriter(procOS); 

     FileInputStream fis = new FileInputStream(file); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(fis)); 
     String send; 

     while ((send = reader.readLine()) != null) { 
      procStdIn.write(send); 
      System.out.println(send); 
      copyStream(procES, System.err); 
      copyStream(procIS, System.out); 
     } 
     procStdIn.write("\r\nexit\r\n"); 
     int exitCode = proc.waitFor(); 
     return exitCode == 0; 
    } 

    private void copyStream(InputStream is, PrintStream err) throws IOException { 
     byte b[] = new byte[ 1024 ]; 
     int length; 
     while (is.available() > 0 && (length = is.read(b)) > 0) { 
      err.write(b, 0, length); 
     } 

}

+0

你看到孩子進程已退出?也許'copyStream'需要在寫入'exit'後最後一次完成? –

+0

@Hemal沒有cild過程仍在運行。 – stacker

回答

3

我懷疑您阻止讀取輸出和錯誤。有關更多詳細信息,請參閱this answer

+0

對不起,copyStream方法不會因爲可用()的調用而被阻塞。 – stacker

+1

感謝問題是mysqls輸入流上丟失的flush()。 – stacker

0

地址:

procStdIn.flush(); 

後:

procStdIn.write("\r\nexit\r\n"); 
+0

你可以解釋一下,而不是隻寫代碼... – eirikir