如何在java应用程序中连续获取批处理cmd输出



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

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

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

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

首先你要阅读InputStream:你从InputStream阅读,你写信给OutputStream看这篇文章

然后使用BufferReader来包装您的OutputStream,并在一段时间循环中逐行阅读。

您还可以捕获错误InputStream。如果看不到任何输出,则进行调试可能会很有用。

下面是使用ping命令的示例。因为我不知道你的tsharp命令是什么。

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("ping www.google.com");
String line = null;
BufferedReader inputStreamReader = 
new BufferedReader(new InputStreamReader(proc.getInputStream()));
while ((line = inputStreamReader.readLine()) != null) {
System.out.println(line);
}
BufferedReader errorStreamReader = 
new BufferedReader(new InputStreamReader(proc.getErrorStream()));
while ((line = errorStreamReader.readLine()) != null) {
System.out.println(line);
}

这正是我的代码。Ping comand 很快结束,所以如果我等待几秒钟,我就会得到结果。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();

最新更新