title: Memory-mapped files in Java
body: <p>I've been trying to write some very fast Java code that has to do a lot of I/O. I'm using a memory mapped file that returns a ByteBuffer:</p>
  <pre><code>public static ByteBuffer byteBufferForFile(String fname){
      FileChannel vectorChannel;
      ByteBuffer vector;
      try {
          vectorChannel = new FileInputStream(fname).getChannel();
      } catch (FileNotFoundException e1) {
          e1.printStackTrace();
          return null;
      }
      try {
          vector = vectorChannel.map(MapMode.READ_ONLY,0,vectorChannel.size());
      } catch (IOException e) {
          e.printStackTrace();
          return null;
      }
      return vector;
  }
  </code></pre>
  <p>The problem that I'm having is that the <code>ByteBuffer</code> <code>.array()</code> method (which should return a <code>byte[]</code> array) doesn't work for read-only files. I want to write my code so that it will work with both memory buffers constructed in memory and buffers read from the disk. But I don't want to wrap all of my buffers a <code>ByteBuffer.wrap()</code> function because I'm worried that this will slow things down. So I've been writing two versions of everything, one that takes a <code>byte[]</code>, the other that takes a <code>ByteBuffer</code>.</p>
  <p>Should I just wrap everything? Or should I double-write everything?</p>