The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.nio  [27 examples] > Files  [7 examples]

e166. Creating a Memory-Mapped File

Mapping a file in memory results in a ByteArray object. To access the byte array, see e159 Getting Bytes from a ByteBuffer and e160 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) {
    }

 Related Examples
e167. Persisting Changes to a Memory-Mapped ByteBuffer
e168. Determining If a ByteBuffer Is Direct
e169. Reading from a Channel with a ByteBuffer
e170. Writing to a Channel with a ByteBuffer
e171. Writing and Appending a ByteBuffer to a File
e172. Copying One File to Another

See also: Byte Buffers    File Locking    Sockets    Streams   


© 2002 Addison-Wesley.