实现获取命令行的返回结果

 1 /**
 2  * @author liuwenlong
 3  * @create 2020-07-24 15:00:39
 4  */
 5 @SuppressWarnings("all")
 6 public class TestRunTime {
 7     public static String exeCmd(String commandStr) {
 8         BufferedReader br = null;
 9         try {
10             Process p = Runtime.getRuntime().exec(commandStr);
11             br = new BufferedReader(new InputStreamReader(p.getInputStream(),"gbk"));
12             String line = null;
13             StringBuilder sb = new StringBuilder();
14             while ((line = br.readLine()) != null) {
15                 sb.append(line + "\n");
16             }
17             return sb.toString();
18         } catch (Exception e) {
19             e.printStackTrace();
20         } finally {
21             if (br != null) {
22                 try {
23                     br.close();
24                 } catch (Exception e) {
25                     e.printStackTrace();
26                 }
27             }
28         }
29         return commandStr;
30     }
31 
32     public static void main(String[] args) {
33         String commandStr = "ping 127.0.0.1";
34         System.out.println(TestRunTime.exeCmd(commandStr));
35     }
36 }

 

posted @ 2020-07-27 18:34  勤快的懒羊羊  阅读(367)  评论(0编辑  收藏  举报