Use a mapped file to read a text file : New IO « File Input Output « Java






Use a mapped file to read a text file

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

public class MainClass {
  public static void main(String args[]) {
    FileInputStream fileInputStream;
    FileChannel fileChannel;
    long fileSize;
    MappedByteBuffer mBuf;

    try {
      fileInputStream = new FileInputStream("test.txt");
      fileChannel = fileInputStream.getChannel();
      fileSize = fileChannel.size();
      mBuf = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);

      for (int i = 0; i < fileSize; i++)
        System.out.print((char) mBuf.get());

      fileChannel.close();
      fileInputStream.close();
    } catch (IOException exc) {
      System.out.println(exc);
      System.exit(1);
    }
  }
}

           
       








Related examples in the same category

1.FileChannel: map(FileChannel.MapMode mode,long position,long size)
2.Write to a file using the new I/O
3.Write to a mapped file
4.Copy a file using NIO
5.Write A String As Bytes
6.Use New Java IO to write string into a file