我正在开发一个Java程序,我从动态的未知块中读取文件。也就是说,每个数据块将不总是相同的大小,并且在读取数据时确定大小。对于I / O我使用MappedByteBuffer(文件输入大小为MB)。
我的目标:
我的约束:
我尝试过的事情:
我试图找到一种不会破坏快速I / O目的的方法。任何建议都将不胜感激。
其他信息:
这里有一些伪代码:
circular_buffer[] = read first 128 bytes
rolling_hash = hash(buffer[])
block_storage = ??? // this is the data structure I'd like to use
while file has more text
b = next byte
add b to block_storage
add b to next index in circular_buffer (if reached end, start adding/overwriting front)
shift rolling_hash one byte to the right
if hash has a certain characteristic
process block_storage as a byte[] //should contain entire block of data
正如您所看到的,我一次只读取一个字节,并重复存储/覆盖该一个字节。但是,一旦我进入处理阶段,我希望能够访问块中的所有信息。也没有预定的最大块大小,所以我无法预先分配。
答案 0 :(得分:1)
在我看来,你需要一个动态增长的缓冲区。您可以使用内置的BytaArrayOutputStream来实现这一目标。它将自动增长以存储写入其中的所有数据。您可以使用write(int b)和toByteArray()来实现add b to block_storage
和process block_storage as a byte[]
。
但请注意 - 这条小溪将无限增长。你应该在它周围实现一些健全性检查,以避免耗尽所有内存(例如,写入它的计数字节,并在超过合理数量时抛出异常)。还要确保在使用块后关闭并丢弃对流的引用,以允许GC释放内存。
编辑:正如@marcman指出的那样,缓冲区可以是reset()。