简体   繁体   English

Java.NIO InvalidIndexException-如何随机访问大型文件进行读写

[英]Java.NIO InvalidIndexException - how to read and write with random access to large files

I've created a java.nio.MappedByteBuffer around a java.io.RandomAccessFile (a file which is only 54 KB in size). 我已经在java.io.RandomAccessFile (一个只有54 KB大小的文件)周围创建了一个java.nio.MappedByteBuffer The resulting MappedByteBuffer has a "capacity" and "limit" of around 12 KB, so when I try to invoke mybytebuffer.get(i > 13044) or mybytebuffer.put(i > 13044, value) it throws an InvalidIndexException . 生成的MappedByteBuffer具有大约12 KB的“容量”和“限制”,因此当我尝试调用mybytebuffer.get(i > 13044)mybytebuffer.put(i > 13044, value)它将引发InvalidIndexException

All of this behavior is documented in Sun's official javadocs. Sun的官方javadocs中记录了所有这些行为。 My question is how I can use java.nio ByteBuffers to read or write anywhere in the file (I need random access). 我的问题是如何使用java.nio ByteBuffers读取或写入文件中的任何位置(我需要随机访问)。 I can't seem to find an example or documentation of Java NIO that illustrates non-sequential access. 我似乎找不到Java NIO的示例或说明非顺序访问的文档。

MappedByteBuffer can access files randomly...it is a 'direct byte buffer'. MappedByteBuffer可以随机访问文件...这是一个“直接字节缓冲区”。 (Specifically, it uses the OS's virtual memory subsystem to map the file to memory.) (特别是,它使用操作系统的虚拟内存子系统将文件映射到内存。)

You can access bytes randomly as in the code snippet here: 您可以按照以下代码段中的顺序随机访问字节:

public void doIt() throws FileNotFoundException, IOException {
    File file = new File("myfile");
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    FileChannel fc = raf.getChannel();      
    MappedByteBuffer mbb = fc.map(MapMode.READ_WRITE, 0, file.length());

    //get a random byte
    byte b1 = mbb.get(SOME_RANDOM_BYTE); 

    //get another random byte
    mbb.position(SOME_OTHER_BYTE_POSITION);
    byte b2 = mbb.get();
}

You can move about the MBB and access bytes (both reading and writing) as you need to. 您可以根据需要移动MBB并访问字节(读和写)。

MappedByteBuffers do not themselves offer random access. MappedByteBuffer本身并不提供随机访问。 This is a misunderstanding. 这是一个误会。 Use a SeekableByteChannel for random access. 使用SeekableByteChannel进行随机访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM