转载自 https://blog.csdn.net/zyf_balance/article/details/51692065
1 public static void main(String[] args) { 2 try { 3 // 执行ping命令 4 Process process = Runtime.getRuntime().exec("cmd /c e:&dir"); 5 BufferedReader br = new BufferedReader(
new InputStreamReader( process.getInputStream(), Charset.forName("GBK") )
); 6 String line = null; 7 while ((line = br.readLine()) != null) { 8 System.out.println(line); 9 } 10 } catch (IOException e) { 11 e.printStackTrace(); 12 } 13 }
我的代码
1 package net.bigwrok; 2 3 import java.io.BufferedReader; 4 import java.io.InputStreamReader; 5 import java.nio.charset.Charset; 6 7 public class Test2_net { 8 public static void main(String[] args) { 9 10 11 12 BufferedReader br = null; 13 try { 14 Process p = Runtime.getRuntime().exec("ping 127.0.0.1"); 15 br = new BufferedReader(new InputStreamReader(p.getInputStream(),Charset.forName("GBK"))); 16 String line = null; 17 StringBuilder sb=new StringBuilder(); 18 while ((line = br.readLine()) != null) { 19 sb.append(line+" "); 20 } 21 System.out.println(sb.toString()); 22 23 } catch (Exception e) { 24 e.printStackTrace(); 25 } finally { 26 27 if (br != null) { 28 try { 29 br.close(); 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } 33 } 34 } 39 40 } 41 42 }
结果