process java
- IT科技
- 關注:2.47W次
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
java process是什麼?一起來看看小編今天的分享吧!
在專案開發中,經常會遇到呼叫其它程式功能的業務需求,在java中通常有兩種實現方法,包括:
Runtime runtime = Runtime.getRuntime();Process p =runtime.exec(cmd);
和
Process p=new ProcessBuilder(cmd).start();
在這裡就需要認識一下process類,process是一個抽象的類,它包含6個抽象的方法:
abstract voiddestroy() 殺掉子程序。abstract intexitValue() 返回子程序的出口值。abstract InputStreamgetErrorStream() 獲取子程序的錯誤流。abstract InputStreamgetInputStream() 獲取子程序的輸入流。abstract OutputStreamgetOutputStream() 獲取子程序的輸出流。abstract intwaitFor() 導致當前執行緒等待,如有必要,一直要等到由該 Process 物件表示的程序已經終止。
以“ping 百度網址”為例:
import java.io.IOException; public class ProcessDemo { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec("ping www.baidu.com"); System.out.println("任務執行完畢!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
由於Process提供了WaitFor和getInputStream兩個方法,這兩個方法都阻塞java執行緒,使呼叫ping被掛到後臺執行,程式直接列印“任務執行完畢!”,而我們想要的效果是先把ping操作執行完成後,再輸出“任務執行完畢!”,可以等待指令碼返回或結束後,再繼續執行java程式:
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader; public class ProcessDemo { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec("ping www.baidu.com"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream(),"gbk")); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } System.out.println("任務執行完畢!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
import java.io.IOException; public class ProcessDemo { public static void main(String[] args) { try { Process process = Runtime.getRuntime().exec("ping www.baidu.com"); process.waitFor(); System.out.println("任務執行完畢!"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
這樣就完成了process的Java程式操作。
- 文章版權屬於文章作者所有,轉載請註明 https://shqsg.com/dianzi/gz6mgw.html