Java執(zhí)行cmd命令兩種實現(xiàn)方法解析
一般java在執(zhí)行CMD命令時,通常是使用Runtime.getRuntime.exec(command)來執(zhí)行的,這個方法有兩種細(xì)節(jié)要注意:
1.一般執(zhí)行方法,代碼如下,這種方法有時執(zhí)行exe時會卡在那里。
//一般的執(zhí)行方法,有時執(zhí)行exe會卡在那 stmt要執(zhí)行的命令 public static void executive(String stmt) throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); //獲取Runtime實例 //執(zhí)行命令 try { String[] command = {'cmd', '/c', stmt}; Process process = runtime.exec(command); // 標(biāo)準(zhǔn)輸入流(必須寫在 waitFor 之前) String inStr = consumeInputStream(process.getInputStream()); // 標(biāo)準(zhǔn)錯誤流(必須寫在 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('執(zhí)行成功'); } else {System.out.println('執(zhí)行失敗' + 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.第二種方法是先生成一個緩存文件,用來緩存執(zhí)行過程中輸出的信息,這樣在執(zhí)行命令的時候不會卡。代碼如下:
//這個方法比第一個好,執(zhí)行時不會卡 stmt要執(zhí)行的命令 public static void aaa(String stam){ BufferedReader br = null; try { File file = new File('D:daemonTmp'); File tmpFile = new File('D:daemonTmptemp.tmp');//新建一個用來存儲結(jié)果的緩存文件 if (!file.exists()){file.mkdirs(); } if(!tmpFile.exists()) {tmpFile.createNewFile(); } ProcessBuilder pb = new ProcessBuilder().command('cmd.exe', '/c', stam).inheritIO(); pb.redirectErrorStream(true);//這里是把控制臺中的紅字變成了黑字,用通常的方法其實獲取不到,控制臺的結(jié)果是pb.start()方法內(nèi)部輸出的。 pb.redirectOutput(tmpFile);//把執(zhí)行結(jié)果輸出。 pb.start().waitFor();//等待語句執(zhí)行完成,否則可能會讀不到結(jié)果。 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('執(zhí)行完成'); } catch (Exception e) { e.printStackTrace(); } finally { if(br != null) {try { br.close();} catch (IOException e) { e.printStackTrace();} } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. React+umi+typeScript創(chuàng)建項目的過程2. ASP中常用的22個FSO文件操作函數(shù)整理3. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析4. SharePoint Server 2019新特性介紹5. .Net core 的熱插拔機制的深入探索及卸載問題求救指南6. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯誤頁的問題7. 讀大數(shù)據(jù)量的XML文件的讀取問題8. ASP編碼必備的8條原則9. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁10. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp
