Java MappedByteBuffer class

Introduction

For reading a file, use MapMode.READ_ONLY.

To read and write, use MapMode.READ_WRITE.

MapMode.PRIVATE creates a private copy of the file.

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Paths;

public class Main {
   public static void main(String args[]) {

      try (FileChannel fChan = (FileChannel) Files.newByteChannel(Paths.get("test.txt"))) {

         long fSize = fChan.size();
         MappedByteBuffer mBuf = fChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);

         for (int i = 0; i < fSize; i++){
            System.out.print((char) mBuf.get());
         }//from   ww w  .jav a 2 s .  c o  m
         System.out.println();

      } catch (InvalidPathException e) {
         System.out.println("Path Error " + e);
      } catch (IOException e) {
         System.out.println("I/O Error " + e);
      }
   }
}



PreviousNext

Related