Mega Code Archive

 
Categories / Java Tutorial / File
 

Mapping an entire file into memory for reading

import java.io.File; import java.io.FileInputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public class MainClass {   public static void main(String[] args) throws Exception {     long length = new File("test.txt").length();     MappedByteBuffer in = new FileInputStream("test.txt").getChannel().map(         FileChannel.MapMode.READ_ONLY, 0, length);     int i = 0;     while (i < length)       System.out.print((char) in.get(i++));   } }