標籤:trace article str 迴圈 process error physical 程式 file
一、java執行cmd命令的三種方式:http://www.jb51.net/article/80829.htm
參考:https://www.cnblogs.com/zhufu9426/p/7928570.html,http://blog.csdn.net/Roy_70/article/details/51505314
二、cmd命令參考:https://baike.baidu.com/item/CMD%E5%91%BD%E4%BB%A4/9684689?fr=aladdin#3
方式一:
public static String checkPhysicalAddress() { String physicalAddress = "read MAC error!"; try { String line; Process process = Runtime.getRuntime().exec("cmd /c ipconfig /all"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream(),"gbk"));//使用gbk編碼解決輸出亂碼問題 while ((line = bufferedReader.readLine()) != null) { if (line.indexOf("Physical Address. . . . . . . . . :") != -1) { if (line.indexOf(":") != -1) { physicalAddress = line.substring(line.indexOf(":") + 2); break; // 找到MAC,退出迴圈 } } } process.waitFor(); } catch (Exception e) { e.printStackTrace(); } return physicalAddress; }
方式二:
public static void startProgram(String programPath) throws IOException { log.info("啟動應用程式:" + programPath); if (StringUtils.isNotBlank(programPath)) { try { String programName = programPath.substring(programPath.lastIndexOf("/") + 1, programPath.lastIndexOf(".")); List<String> list = new ArrayList<String>(); list.add("cmd.exe"); list.add("/c"); list.add("start"); list.add("\"" + programName + "\""); list.add("\"" + programPath + "\""); ProcessBuilder pBuilder = new ProcessBuilder(list); pBuilder.start(); } catch (Exception e) { e.printStackTrace(); log.error("應用程式:" + programPath + "不存在!"); } } }
方式三:
public static void startProgram(String programPath) throws IOException { log.info("啟動應用程式:" + programPath); if (StringUtils.isNotBlank(programPath)) { try { Desktop.getDesktop().open(new File(programPath)); } catch (Exception e) { e.printStackTrace(); log.error("應用程式:" + programPath + "不存在!"); } } }
三、Java中使用Runtime和Process類運行外部程式
四、process中waitFor()問題
引用:JDK協助文檔上這麼說:如有必要,一直要等到由該 Process 對象表示的進程已經終止。如果已終止該子進程,此方法立即返回。但是直接調用這個方法會導致當前線程阻塞,直到退出子進程。對此JDK文檔上還有如此解釋:因為本地的系統對標準輸入和輸出所提供的緩衝池有效,所以錯誤的對標準輸出快速的寫入何從標準輸入快速的讀入都有可能造成子進程的所,甚至死結。好了,問題的關鍵在緩衝區這個地方:可執行程式的標準輸出比較多,而運行視窗的標準緩衝區不夠大,所以發生阻塞。接著來分析緩衝區,哪來的這個東西,當Runtime對象調用exec(cmd)後,JVM會啟動一個子進程,該進程會與JVM進程建立三個管道串連:標準輸入,標準輸出和標準錯誤流。假設該程式不斷在向標準輸出資料流和標準錯誤流寫資料,而JVM不讀取的話,當緩衝區滿之後將無法繼續寫入資料,最終造成阻塞在waitfor()這裡。 知道問題所在,我們解決問題就好辦了。查看網上說的方法多數是開兩個線程在waitfor()命令之前讀出視窗的標準輸出緩衝區和標準錯誤流的內容。
- p = Runtime.getRuntime().exec("notepad.exe");
- p.waitFor();
總結:在方法 exec("notepad.exe"); 調用的其它程式沒有終止之前,p.waitFor()表示在此處等待,不繼續執行後面的代碼,類似於回呼函數
java中執行cmd命令