title: How to memory map (mmap) a linux block device (e.g. /dev/sdb) in Java?
body: <p>I can read/write a linux block device with Java using <code>java.nio</code>. The following code works:</p>
  
  <pre><code>Path fp = FileSystems.getDefault().getPath("/dev", "sdb");
  FileChannel fc = null;
  try {
    fc = FileChannel.open(fp, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE));
  } catch (Exception e) {
    System.out.println("Error opening file: " + e.getMessage());
  }
  ByteBuffer buf = ByteBuffer.allocate(50);
  try {
    if(fc != null)
      fc.write(buf);
  } catch (Exception e) {
    System.out.println("Error writing to file: " + e.getMessage());
  }
  </code></pre>
  
  <p>However, memory mapping does not work. The following code <strong>fails</strong>:</p>
  
  <pre><code>MappedByteBuffer mbb = null;
  try {
    mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 100);
  } catch (IOException e) {
    System.out.println("Error mapping file: " + e.getMessage());
  }
  </code></pre>
  
  <p>This fails with Error:</p>
  
  <pre><code>java.io.IOException: Invalid argument
      at sun.nio.ch.FileDispatcherImpl.truncate0(Native Method)
      at sun.nio.ch.FileDispatcherImpl.truncate(FileDispatcherImpl.java:79)
      at sun.nio.ch.FileChannelImpl.map(FileChannelImpl.java:817)
  </code></pre>
  
  <p>Is there a work around to this? Perhaps by using a different library? I read somewhere that maybe by using JNI I could do this, but I couldn't find any sources.</p>