Java FileChannel map to MappedByteBuffer

Description

Java FileChannel map to MappedByteBuffer

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
   public static void main(String args[]) {
      FileInputStream fIn = null;
      FileChannel fChan = null;/*from  w  w  w .jav  a2s.  c o  m*/
      long fSize;
      MappedByteBuffer mBuf;

      try {
         fIn = new FileInputStream("test.txt");
         fChan = fIn.getChannel();
         fSize = fChan.size();
         mBuf = fChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);
         for (int i = 0; i < fSize; i++)
            System.out.print((char) mBuf.get());

      } catch (IOException e) {
         System.out.println("I/O Error " + e);
      } finally {
         try {
            if (fChan != null)
               fChan.close(); // close channel
         } catch (IOException e) {
            System.out.println("Error Closing Channel.");
         }
         try {
            if (fIn != null)
               fIn.close(); // close file
         } catch (IOException e) {
            System.out.println("Error Closing File.");
         }
      }
   }
}



PreviousNext

Related