2009-10-14 94 views
0

我有一個Java程序可以在OS中執行特定命令。我也使用Process.waitfor()(如下面的代碼所示)來指示執行是否成功完成或失敗。在操作系統中執行命令的Java

我的問題是,有沒有其他的方式來避免使用process.waitfor(),有沒有辦法使用while循環,並執行某些操作,直到該過程完成?

  Runtime rt = Runtime.getRuntime(); 

     Process p = rt.exec(cmdFull); 

     BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String inStreamLine = null; 
     String inStreamLinebyLine=null; 
     while((inStreamLine = inStream.readLine()) == null) { 
      inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine; 
     } 


     try { 
      rc = p.waitFor(); 

     } catch (InterruptedException intexc) { 
      System.out.println("Interrupted Exception on waitFor: " + 
           intexc.getMessage()); 
     }  

啥子我希望做的,是這樣的

  Runtime rt = Runtime.getRuntime(); 

     Process p = rt.exec(cmdFull); 

     BufferedReader inStream = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String inStreamLine = null; 
     String inStreamLinebyLine=null; 
     while((inStreamLine = inStream.readLine()) == null) { 
      inStreamLinebyLine = inStreamLinebyLine+"\n"+inStreamLine; 
     } 


     try { 

      while ((rc = p.waitFor()) == true) { // This is made up, I don't even think it would work 
       System.out.println('Process is going on...'); 
      } 


     } catch (InterruptedException intexc) { 
      System.out.println("Interrupted Exception on waitFor: " + 
           intexc.getMessage()); 
     }  

感謝,

回答

1

也許這樣的事情會工作。創建一個線程,建議使用@tschaible,然後在超時線程(這是您在代碼中編寫的部分)對該線程進行加入。這將是這個樣子:

Thread t = new Thread(new Runnable() { 

    public void run() { 
    // stuff your code here 
    } 

}); 
t.run(); 

while (t.isAlive()) { 
    t.join(1000); // wait for one second 
    System.out.println("still waiting"); 
} 

這樣做是啓動代碼作爲一個單獨的線程,然後測試,如果胎面完成每一秒。當線程結束並且不再活動時,while循環應該結束。您可能需要檢查InterruptedException,但現在無法對其進行測試。

希望這會讓您朝正確的方向發展。

1

你可以在啓動過程之前生成一個新的線程。

新線程將負責打印出「正在進行中......」或任何需要的內容。

p.waitFor()完成後,啓動進程的主線程將向新線程指示應該停止運行。

1

您可以產生一個新的thread並在線程中等待,通過共享變量定期從主線程檢查等待線程是否已完成。