Java執(zhí)行cmd命令兩種實(shí)現(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實(shí)例 //執(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(); } }/** * 消費(fèi)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);//這里是把控制臺中的紅字變成了黑字,用通常的方法其實(shí)獲取不到,控制臺的結(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. ASP基礎(chǔ)入門第四篇(腳本變量、函數(shù)、過程和條件語句)2. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)3. XML在語音合成中的應(yīng)用4. JSP開發(fā)之hibernate之單向多對一關(guān)聯(lián)的實(shí)例5. jscript與vbscript 操作XML元素屬性的代碼6. 基于PHP做個圖片防盜鏈7. ASP將數(shù)字轉(zhuǎn)中文數(shù)字(大寫金額)的函數(shù)8. Jsp+Servlet實(shí)現(xiàn)文件上傳下載 文件列表展示(二)9. Jsp servlet驗(yàn)證碼工具類分享10. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)
