Java執(zhí)行cmd命令兩種實(shí)現(xiàn)方法解析
一般java在執(zhí)行CMD命令時(shí),通常是使用Runtime.getRuntime.exec(command)來執(zhí)行的,這個(gè)方法有兩種細(xì)節(jié)要注意:
1.一般執(zhí)行方法,代碼如下,這種方法有時(shí)執(zhí)行exe時(shí)會(huì)卡在那里。
//一般的執(zhí)行方法,有時(shí)執(zhí)行exe會(huì)卡在那 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)錯(cuò)誤流(必須寫在 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(); //若有錯(cuò)誤信息則輸出 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.第二種方法是先生成一個(gè)緩存文件,用來緩存執(zhí)行過程中輸出的信息,這樣在執(zhí)行命令的時(shí)候不會(huì)卡。代碼如下:
//這個(gè)方法比第一個(gè)好,執(zhí)行時(shí)不會(huì)卡 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');//新建一個(gè)用來存儲(chǔ)結(jié)果的緩存文件 if (!file.exists()){file.mkdirs(); } if(!tmpFile.exists()) {tmpFile.createNewFile(); } ProcessBuilder pb = new ProcessBuilder().command('cmd.exe', '/c', stam).inheritIO(); pb.redirectErrorStream(true);//這里是把控制臺(tái)中的紅字變成了黑字,用通常的方法其實(shí)獲取不到,控制臺(tái)的結(jié)果是pb.start()方法內(nèi)部輸出的。 pb.redirectOutput(tmpFile);//把執(zhí)行結(jié)果輸出。 pb.start().waitFor();//等待語句執(zhí)行完成,否則可能會(huì)讀不到結(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();} } } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
