java调用dos命令
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
package com; import java.io.BufferedReader; import java.io.InputStreamReader; public class CommonUtils { public static String exeCMD1(String cmd){ cmd = "cmd.exe /c "+cmd; Process process = null; StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { process = Runtime.getRuntime().exec(cmd); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); while(true){ String str = reader.readLine(); if(str==null) break; System.out.println(str); sb.append(str); } process.destroy(); } catch (Exception e) { // TODO: handle exception } return sb.toString(); } public static String exeCMD2(String cmd){ String[] args = new String[]{"cmd","/c",cmd}; Process process = null; StringBuffer sb = new StringBuffer(); BufferedReader reader = null; try { process = Runtime.getRuntime().exec(args); reader = new BufferedReader(new InputStreamReader(process.getInputStream())); while(true){ String str = reader.readLine(); if(str==null) break; System.out.println(str); sb.append(str); } process.destroy(); } catch (Exception e) { // TODO: handle exception } return sb.toString(); } public static void main(String[] args){ CommonUtils.exeCMD1("tree"); CommonUtils.exeCMD1("tree"); } } |