Creating a Memory-Mapped File

Mapping a file in memory results in a ByteArray object. To access the byte array, see Getting Bytes from a ByteBuffer and Putting Bytes into a ByteBuffer.
try {
    File file = new File("filename");

    // Create a read-only memory-mapped file
    FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
    ByteBuffer roBuf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());

    // Create a read-write memory-mapped file
    FileChannel rwChannel = new RandomAccessFile(file, "rw").getChannel();
    ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int)rwChannel.size());

    // Create a private (copy-on-write) memory-mapped file.
    // Any write to this channel results in a private copy of the data.
    FileChannel pvChannel = new RandomAccessFile(file, "rw").getChannel();
    ByteBuffer pvBuf = roChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int)rwChannel.size());
} catch (IOException e) {
}

Comments

13 Jul 2011 - 10:38pm by Anonymous (not verified)

how to read a very large file without using io streams? is ther any other technique

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.