2

I'm learning about Memory Mapped files in java. I would like to know how to write/read to a MappedByteBuffer.

Here's the code I'm using for writing to 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();
            }

        }
    }

I get BufferOverflow Exception while trying to do it.

How do I increase the size of the MappedByteBuffer after reaching the limit while writing, if I do not the know the size of the contents I will write to the file in advance?

For reading, let's take this case, I create an MappedByteBuffer with an intial buffer size, and if reached the end of that initial size, how do i map a different portion of the file

More generally, I have a file , with byte offsets from one part of the file to another, When I read an offset (y) at a point (x), I would like to jump to (y) from (x). How do I do it?

Thanks in advance for helping me out.

  • 1
    You would normally map the entire file, rather than 1k at a time and all these other shenanigans. – user207421 Jan 07 '16 at 09:35
  • Thanks for your reply, So how would i write a huge file ? What should is pass as parameter to FileChannel.map() function ? It asks for a size in advance (which I do not know) – user5756390 Jan 07 '16 at 11:17
  • You wouldn't write it with `MappedByteBuffer` at all. There is no advantage. – user207421 Jan 08 '16 at 05:02

0 Answers0