我已经实现了我自己的课程来阅读pcap
文件。 (二进制文件,即tcpdump的,Wireshark的)为什么InputStream.available()这么耗时?
public class PcapReader implements Iterator<PcapPacket> {
private InputStream is;
public PcapReader (File file) throws FileNotFoundException, IOException {
is = this(new DataInputStream(
new BufferedInputStream(
new FileInputStream(file))));
}
@Override
public boolean hasNext() {
try {
return (is.available() > 0);
} catch (IOException e) {
return false;
}
}
//pseudo code!
@Override
public PcapPacket next() {
is.read(header);
is.read(body);
return new PcapPacket(header, body);
}
//more code here
}
然后,我使用这样的:
PcapReader reader = new PcapReader(file);
while (reader.hasNext()) {
PcapPacket pcapPacket = reader.next();
//process packet
}
文件下测试具有190兆。而且我还使用JVisualVM进行配置。
hasNext()
被称为170万次,时间为7.7秒next()
被称为相同的次数和时间3.6秒
我的主要问题这就是为什么hasNext()
绝对值如此耗时以及两次gre比next
?
我会避免可用()像一个有害生物 - 它的设计破坏(返回一个int!)的初学者,并且你必须在处理IOException的同时实际读取数据。它非常少见的*需要*使用available()。 – Durandal 2013-03-06 15:36:13