首页 > 解决方案 > 如何在java应用程序中连续获取批处理cmd输出

问题描述

我编写了一个程序,它运行批处理命令(tshark)来捕获 2 个 IP 地址之间的数据包大小(连续)。

我使用RuntimeandProcess运行它并process.getOutputStream()获取返回值并在 java 终端中打印它们。

我的问题是打印在两条记录之间暂停(打印 1200 行/停止 10 秒/打印 1200 行)。

你知道在java应用程序中连续读取OutputStream批处理命令的方法吗?

标签: javamultithreadingprocessbufferoutputstream

解决方案


这正是我的代码。Ping 命令很快结束,所以如果我等待几秒钟,我就会得到结果。Tshark 捕获网络流量,因此不会结束。

我的问题是阅读暂停。

这是我的代码:

    String cmd = "c:\\\"Program Files\"\\Wireshark\\tshark.exe -T fields -e frame.len host"+ ipSrc +" and dst "+ ipDst;

    String[] command = {"cmd.exe", "/C", cmd};

    try {
        final Process proc = Runtime.getRuntime().exec(command);
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(proc.getInputStream()));
            String line = "";
            try {
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                }
            } finally {
                reader.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

我也尝试使用线程在终端中写入,但这是同样的问题:

    new Thread() {
            @Override
            public void run() {
                try {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(
                                    process.getInputStream()));
                    String line = "";
                    try {
                        while ((line = reader.readLine()) != null) {
                            System.out.println(line);
                        }
                    } finally {
                        reader.close();
                    }
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }.start();

推荐阅读