Java執行cmd命令兩種實現方法解析
阿新 • • 發佈:2020-07-29
一般java在執行CMD命令時,通常是使用Runtime.getRuntime.exec(command)來執行的,這個方法有兩種細節要注意:
1.一般執行方法,程式碼如下,這種方法有時執行exe時會卡在那裡。
//一般的執行方法,有時執行exe會卡在那 stmt要執行的命令 public static void executive(String stmt) throws IOException,InterruptedException { Runtime runtime = Runtime.getRuntime(); //獲取Runtime例項 //執行命令 try { String[] command = {"cmd","/c",stmt}; Process process = runtime.exec(command); // 標準輸入流(必須寫在 waitFor 之前) String inStr = consumeInputStream(process.getInputStream()); // 標準錯誤流(必須寫在 waitFor 之前) String errStr = consumeInputStream(process.getErrorStream()); new ProcessClearStream(process.getInputStream(),"INFO").start(); new ProcessClearStream(process.getErrorStream(),"ERROR").start(); int proc = process.waitFor(); InputStream errorStream = process.getErrorStream(); //若有錯誤資訊則輸出 if (proc == 0) { System.out.println("執行成功"); } else { System.out.println("執行失敗" + errStr); } } catch (IOException | InterruptedException e) { e.printStackTrace(); } } /** * 消費inputstream,並返回 */ public static String consumeInputStream(InputStream is) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(is,"GBK")); String s; StringBuilder sb = new StringBuilder(); while ((s = br.readLine()) != null) { System.out.println(s); sb.append(s); } return sb.toString(); }
2.第二種方法是先生成一個快取檔案,用來快取執行過程中輸出的資訊,這樣在執行命令的時候不會卡。程式碼如下:
//這個方法比第一個好,執行時不會卡 stmt要執行的命令 public static void aaa(String stam){ BufferedReader br = null; try { File file = new File("D:\\daemonTmp"); File tmpFile = new File("D:\\daemonTmp\\temp.tmp");//新建一個用來儲存結果的快取檔案 if (!file.exists()){ file.mkdirs(); } if(!tmpFile.exists()) { tmpFile.createNewFile(); } ProcessBuilder pb = new ProcessBuilder().command("cmd.exe",stam).inheritIO(); pb.redirectErrorStream(true);//這裡是把控制檯中的紅字變成了黑字,用通常的方法其實獲取不到,控制檯的結果是pb.start()方法內部輸出的。 pb.redirectOutput(tmpFile);//把執行結果輸出。 pb.start().waitFor();//等待語句執行完成,否則可能會讀不到結果。 InputStream in = new FileInputStream(tmpFile); br= new BufferedReader(new InputStreamReader(in)); String line = null; while((line = br.readLine()) != null) { System.out.println(line); } br.close(); br = null; tmpFile.delete();//卸磨殺驢。 System.out.println("執行完成"); } catch (Exception e) { e.printStackTrace(); } finally { if(br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。