2010-09-14 76 views
2

我写,我需要对整个运行的应用程序的生命周期在后台运行的过程的Java应用程序运行的Java运行时进程。获取背景

这是我有:

Runtime.getRuntime().exec("..(this works ok).."); 
Process p = Runtime.getRuntime().exec("..(this works ok).."); 
InputStream is = p.getInputStream(); 
InputStreamReader isr = new InputStreamReader(is); 
BufferedReader br = new BufferedReader(isr); 

所以,基本上我打印出每个br.readLine()

,我是不知道的事情是如何在我的应用程序中实现此代码,因为无论我把它(与Runnable接口),它会阻止其他代码运行(如预期)。

我用了Runnable,螺纹,SwingUtilities类的,并没有什么作品...

任何帮助,将不胜感激:)

回答

1

可以读取输入流(即br.readLine())在一个线程。这样,它总是在后台运行。

我们已经在我们的应用中实现这一点的方式大致如下图所示:

业务逻辑,即您可以调用脚本的地方:

// Did something... 

InvokeScript.execute("sh blah.sh"); // Invoke the background process here. The arguments are taken in processed and executed. 

// Continue doing what you were doing 

InvokeScript.execute()看起来像如下:

InvokeScript.execute(String args) { 
// Process args, convert them to command array or whatever is comfortable 

Process p = Runtime.getRuntime().exec(cmdArray); 

ReaderThread rt = new ReaderThread(p.getInputStream()); 
rt.start(); 
} 

ReaderThread应该继续读取您开始的进程的输出,只要它持续。

请注意,上面只是一个伪代码。

+0

感谢pavanlimo,关于何时何地启动Process = Runtime.getRuntime()。exec(? – phillyville 2010-09-14 16:59:24

+0

请参阅我上面的编辑 – pavanlimo 2010-09-14 17:13:53

+0

感谢一堆pavanlimo,我测试了浏览器上的代码和它就像一个魅力,但我实际上是寻找东西的Java桌面应用程序。一次你知道InvokeScript和ReaderThread的Java中的等价物? – phillyville 2010-09-14 18:08:48