zoukankan      html  css  js  c++  java
  • [Java]在xp系统下java调用wmic命令获取窗口返回信息无反应(阻塞)的解决方案

    背景:本人写了一段java代码,调用cmd命令“wmic ...”来获取系统cpu、mem、handle等资源信息。在win7操作系统下运行没有问题,在xp系统下却发现读取窗口反馈信息时无反应(阻塞),但在cmd命令行窗口运行是没问题。经过多番查找,终于找到了解决方法。

    原代码:

    public static String getCmdReturn(String cmdcomand) {
                
                String CmdReturn="";
                String line=null;
                Runtime run = Runtime.getRuntime();
                String test="C://Windows//system32//wbem//wmic.exe process where ProcessId='6024' get ThreadCount";   //调试使用
                try {
                    Process process = run.exec(test);  //test为调试使用,原为cmdcomand入参         
                    BufferedReader  bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));    
                    while ((line = bufferedReader.readLine()) != null) {  
                        CmdReturn=CmdReturn+line;
                    }
                    bufferedReader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    // TODO: handle exception
                }
                return CmdReturn;
            }

    修改后的代码:

    public static String getCmdReturn_wmic(String exe, String cmdcomand)
                throws IOException {

            String CmdReturn = "";
            String line = null;
            BufferedReader br = null;
            InputStream is = null;

            String test1="wmic.exe";//调试使用

            String test2=" process where ProcessId='6024' get ThreadCount "//调试使用

            try {
                Process process = Runtime.getRuntime().exec(test1);//test1为调试使用,原为exe入参
                is = process.getInputStream();
                OutputStreamWriter ow = new OutputStreamWriter(
                        process.getOutputStream());
                ow.write(test2);//test2为调试使用,原为cmdcomand入参
                ow.flush();
                ow.close();
                br = new BufferedReader(new InputStreamReader(is));
                int linenum=1;

                while ((line = br.readLine()) != null) {
                    linenum=linenum+1;
                    if(linenum==5){
                        CmdReturn = CmdReturn + line;
                        break;
                    }
                    
                }

            } catch (Exception e) {
                e.printStackTrace();
                // TODO: handle exception
            } finally {
                br.close();
            }

            return CmdReturn;

        }

  • 相关阅读:
    Javascript函数声明和函数表达式
    浅谈getAttribute兼容性
    js数组去重的三种常用方法总结
    说说JSON和JSONP,也许你会豁然开朗
    web安全之跨站请求伪造
    javascript中对象的深度克隆
    三种方式实现元素水平居中显示与固定布局和流式布局概念理解
    js dom element 属性整理(原创)
    ul下的li浮动,如何是ul有li的高度
    js数组去重的4个方法
  • 原文地址:https://www.cnblogs.com/whylaughing/p/7151367.html
Copyright © 2011-2022 走看看