java - 如何在java应用程序中连续获取批处理cmd输出
问题描述
我编写了一个程序,它运行批处理命令(tshark)来捕获 2 个 IP 地址之间的数据包大小(连续)。
我使用Runtime
andProcess
运行它并process.getOutputStream()
获取返回值并在 java 终端中打印它们。
我的问题是打印在两条记录之间暂停(打印 1200 行/停止 10 秒/打印 1200 行)。
你知道在java应用程序中连续读取OutputStream
批处理命令的方法吗?
解决方案
这正是我的代码。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();
推荐阅读
- mysql - MySQL 错误 1054,因为列是计算的
- python - Py3 ThreadPoolExecutor:如何获取剩余项目的数量直到执行
- reactjs - 为什么我不能在 redux useSelector 上使用 map?
- reactjs - 为什么 redux 的 combine reducer 在使用 typescript 和 react-redux-firebase 时会抱怨方法重载?
- python - Python 代码无法运行,我不知道如何修复它
- powershell - 自定义输出 Get-fsrmQuota 报告
- primefaces - 多次调用 LazyDataModel 初始加载
- javascript - Angular - 将具有页面大小的值传递给另一个组件 - currentValue undefined 错误
- newrelic - 具有新遗物集成的 Quarkus (javaagent)
- android - 谁将 touchEvent 传递给 Activity?