Persisting Changes to a Memory-Mapped ByteBuffer - Java File Path IO

Java examples for File Path IO:ByteBuffer

Description

Persisting Changes to a Memory-Mapped ByteBuffer

Demo Code

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] argv) throws Exception {
    try {/*from w  ww.j  a v a2  s  .  c o  m*/
      // 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 Tutorials