2012-07-25 64 views
3

我正在寫一個Java GUI的應用程序,它調用一些FORTRAN代碼。我想返回一個文件(solution.ps),該文件基於FORTRAN代碼中的更改進行更新和編譯,這些更改是在我的ActionPerformed方法中創建的。然而,我目前使用的代碼只是返回文件的舊版本,而不是等待cmd編譯的更新結果。有沒有辦法讓cmd在完成下一步之前等待進程運行? (它工作正常運行直接從cmd)cmd java等待進程

我已經搜索,但無法找到任何東西,除了process.waitFor()這似乎不會暫停在正確的點執行。也試過Thread.waitFor()。

我在想這可能對任何想要將用戶輸入發送到另一個程序並返回使用這些輸入的編譯結果有用。

無論如何,這裏的代碼,預先感謝任何幫助,我希望我明確的問題。

String[] command ={"cmd",}; 
     try { 
      Process p = Runtime.getRuntime().exec(command); 
      new Thread(new SyncPipe(p.getErrorStream(), System.err)).start(); 
      new Thread(new SyncPipe(p.getInputStream(), System.out)).start(); 
      PrintWriter stdin = new PrintWriter(p.getOutputStream()); 
      stdin.println("cd c:\\g77");  
      stdin.println("g77setup.bat"); 
      stdin.println("cd c:\\users\\laurence\\workspace\\areaplanner"); 
      stdin.println("g77 -O4 genpack.f -o genpack"); 
      stdin.println("genpack"); 
      stdin.println("5"); 
      /* 
      * The following line sets the time to run the FORTRAN code for 
      * - need to wait for this to complete before calling mpost 
      */ 
      stdin.println("30"); 

      stdin.println("mpost solution.mp"); 
      stdin.println("latex solution.tex"); 
      stdin.println("dvips solution.dvi -o solution.ps"); 
      stdin.close(); 
      } catch(IOException e4){} 
+0

我不明白你的問題。這是一個CMD或Java問題?等待流程在完成下一步之前運行?_下一步是什麼? – poussma 2012-07-25 12:03:34

+0

兩者,我認爲。我不希望線路「mpost solution.mp」被調用,直到FORTRAN代碼運行30秒。在上面的FORTRAN代碼運行30秒,但在上面的代碼中重新編譯之前,上面代碼片段後面的Java代碼將返回舊版本的solution.ps。 – user1551429 2012-07-25 12:07:14

回答

3

您只能運行windows shell命令。要修復,建議先寫批處理文件,並等待其完成:

String command = "cmd /c mybatchfile.bat"; 
Process p = Runtime.getRuntime().exec(command); 
p.waitFor(); 

再弄段的第一組命令已完成之前揭開序幕,你將不得不寫另一個批處理文件並重覆上述。確保你有兩個進程然後在不同的線程。

+1

我一直在嘗試這個,我幾乎得到了一個完整的工作解決方案。這絕對是走下坡路,感謝您的幫助! – user1551429 2012-07-26 10:32:03

+0

沒問題。隨時'剔'我的迴應:) – Reimeus 2012-07-26 10:35:36

-1

嘗試使用waitFor以使當前線程等待進程完成其作業。

Process p = Runtime.getRuntime().exec(command); 
p.waitFor() 

代碼中的命令不完整。並且建議使用ProcessBuilder.start()而不是Process