java执行cmd命令以及乱码问题

直接上代码:

private static String command=" netstat -ano  ";
    public static void main(String[] args) {
        Process p = null;try {
            p = Runtime.getRuntime().exec(command);
            InputStream fis=p.getInputStream();
            BufferedReader br=new BufferedReader(new  				   InputStreamReader(fis, Charset.forName("GBK")));
            String line=null;
            while((line=br.readLine())!=null)
            {
                if (line.contains("LISTENING")){
                    System.out.println( line );
                }
 }
  } catch (IOException  e) {
        e.printStackTrace();
    }
    }

完善:

 private static void windows(String port) {
        List<String> pids = new ArrayList<>();
        String cmd = " cmd /c netstat -ano|findstr  " + port;
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(cmd);
            // Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
            //针对这种情况,我们只需要将子进程的stream重定向出来即可。
            InputStream fis = p.getInputStream();
            //用缓冲器读行
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("GBK")));
            String line = null;
            //直到读完为止
            while ((line = br.readLine()) != null) {
                pid = line.split(" ")[line.split(" ").length - 1];
                if (pids.contains(pid)) {
                    continue;
                } else {
                    pids.add(pid);
                }
                System.out.println(pid);
                taskList(pid);

}
    p.waitFor();
    br.close();
    p.destroy();
} catch (Exception e) {
    e.printStackTrace();
}
}

private static void taskList(String pid) {
        String cmd = " cmd /c tasklist|findstr " + pid;

        Process p = null;
        try {
            p = Runtime.getRuntime().exec(cmd);
            // Runtime.exec()创建的子进程公用父进程的流,不同平台上,父进程的stream buffer可能被打满导致子进程阻塞,从而永远无法返回。
            //针对这种情况,我们只需要将子进程的stream重定向出来即可。

            InputStream fis = p.getInputStream();

            //用缓冲器读行
            BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("GBK")));
            String line = null;
            //直到读完为止
            while ((line = br.readLine()) != null) {


                System.out.println(line.split(" ")[0]);

            }
            p.waitFor();
            br.close();
            p.destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值