2

我正在学习 java 中的内存映射文件。我想知道如何写入/读取 MappedByteBuffer。

这是我用于写入 MappedByteBuffer 的代码。

private static void write(String strFilePath) {

        File fl = new File(strFilePath);
        FileChannel fChannel = null;
        RandomAccessFile rf = null;
        MappedByteBuffer mBBuffer = null;
        try {

            rf = new RandomAccessFile(fl, "rw");
            fChannel = rf.getChannel();

            mBBuffer = fChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1024  );

            for(int i =0;i<10030;i++) {

                if(i == mBBuffer.limit()) {
                    mBBuffer = fChannel.map(FileChannel.MapMode.READ_WRITE,i+1,1024);
                }
                mBBuffer.put((byte)'a');
            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                if(fChannel != null) {
                    fChannel.close();
                }
                if(rf != null) {
                    rf.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

尝试执行此操作时出现 BufferOverflow 异常。

在写入时达到限制后如何增加 MappedByteBuffer 的大小,如果我不知道我将提前写入文件的内容的大小?

为了阅读,让我们以这种情况为例,我创建一个具有初始缓冲区大小的 MappedByteBuffer,如果达到该初始大小的末尾,我如何映射文件的不同部分

更一般地说,我有一个文件,从文件的一部分到另一部分的字节偏移量,当我在点 (x) 读取偏移量 (y) 时,我想从 (x) 跳转到 (y)。我该怎么做?

提前感谢您帮助我。

4

0 回答 0