java中執行cmd命令


一、java執行cmd命令的三種方式:http://www.jb51.net/article/80829.htm

參考:https://www.cnblogs.com/zhufu9426/p/7928570.htmlhttp://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()命令之前讀出窗口的標准輸出緩沖區和標准錯誤流的內容。

  1.  p = Runtime.getRuntime().exec("notepad.exe");  
  2.  p.waitFor();  

總結:在方法 exec("notepad.exe");   調用的其它程序沒有終止之前,p.waitFor()表示在此處等待,不繼續執行后面的代碼,類似於回調函數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM