360SDN.COM

首页/Java/列表

Java调用命令行并获取执行结果

来源:  2018-01-16 14:34:47    评论:0点击:

    import java.io.BufferedReader;  
    import java.io.InputStreamReader;  
      
    public class Command {  
        public static void exeCmd(String commandStr) {  
            BufferedReader br = null;  
            try {  
                Process p = Runtime.getRuntime().exec(commandStr);  
                br = new BufferedReader(new InputStreamReader(p.getInputStream()));  
                String line = null;  
                StringBuilder sb = new StringBuilder();  
                while ((line = br.readLine()) != null) {  
                    sb.append(line + "\n");  
                }  
                System.out.println(sb.toString());  
            } catch (Exception e) {  
                e.printStackTrace();  
            }   
            finally  
            {  
                if (br != null)  
                {  
                    try {  
                        br.close();  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        }  
      
        public static void main(String[] args) {  
            String commandStr = "ping www.taobao.com";  
            //String commandStr = "ipconfig";  
            Command.exeCmd(commandStr);  
        }  
    }
为您推荐

友情链接 |九搜汽车网 |手机ok生活信息网|ok生活信息网|ok微生活
 Powered by www.360SDN.COM   京ICP备11022651号-4 © 2012-2016 版权