The Java Developers Almanac 1.4


Order this book from Amazon.

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

e167. Persisting Changes to a Memory-Mapped ByteBuffer

Changes to a memory-mapped ByteBuffer are not necessarily sent immediately to the underlying storage device. In some applications, such as with a memory-mapped register, the change should be sent immediately. The MappedByteBuffer.force() method is used to force all changes to the underlying storage device immediately.
    try {
        // Create a ByteBuffer on a memory-mapped file
        File file = new File("filename");
        FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
        MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE, 0, (int)channel.size());
    
        // Make a change to the ByteBuffer
        buf.put(0, (byte)0xFF);
    
        // Force the change to the file system
        buf.force();
    
        // Close the file
        channel.close();
    } catch (IOException e) {
    }

 Related Examples
e166. Creating a Memory-Mapped File
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.