4

I'm reading an unknown number of objects from a gzipped file in Kryo:

Input input = new Input(new GZIPInputStream(Files.newInputStream(inputFile)));

The problem is: How do I detect when I've read the last object from the file? When I'm writing the objects I don't know in advance how many I will be writing, so I can't include a count of the objects at the start of the file.

I could have some kind of "dummy" object that I write at the end of the file to indicate that it's the last one, but that seems ugly.

4

3 回答 3

3

读取每个对象后使用 Input#eof() 检查是否到达流的末尾。

于 2013-06-19T21:58:13.157 回答
1

由于某种原因,input.eof() 无法有效检测 EOF,例如,此代码导致com.esotericsoftware.kryo.KryoException: Buffer underflow.

while (!input.eof())
{
    SomeClass someObject = kryo.readObject(input, SomeClass.class);
    // ...
}

作为一种解决方法,我做了这样的事情:

while (true)
{
    try
    {
        SomeClass someObject = kryo.readObject(input, SomeClass.class);
        // ...
    }
    catch(KryoException ke)
    {
        break;
    }
}

编辑:我使用的是 jar 版本 2.21,但 eof 与 2.22.cloudera.1 一起使用。

于 2013-11-18T20:17:00.830 回答
1

对于最新的 (3.0.3) kryo 库,您可以使用 input.eof()。对于较旧的用户,使用 input.available() 会降低性能(几乎慢 8 倍)。

while(input.available() > 0){
  someObject = kryo.readObject(input, SomeClass.class);
  i++;
}
于 2015-10-16T06:22:03.037 回答