// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package mapfile;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;

public class Read3 {
	private static final int OFFSET = 0;
	private static final int SIZE = 1000000000;
	private static void test(String fnm) throws IOException {
		System.out.printf("%s %s / %s %s\n", System.getProperty("java.vendor"), System.getProperty("java.version"), System.getProperty("os.name"), System.getProperty("os.version"));
		long t1 = System.currentTimeMillis();
		try(FileChannel fc = FileChannel.open(Paths.get(fnm))) {
			ByteBuffer bb = fc.map(MapMode.READ_ONLY, OFFSET, SIZE);
			bb.rewind();
			int n = 0;
			for(int ix = 0; ix < SIZE; ix++) {
				byte b = bb.get(ix);
				if(b == '\n') {
					n++;
				}
			}
			System.out.printf("%d lines\n", n);
		}
		long t2 = System.currentTimeMillis();
		System.out.printf("Map file to memory : %d ms\n", t2 - t1);
	}
	public static void main(String[] args) throws IOException {
		for(int i = 0; i < 3; i++) {
			test(args[0]);
		}
	}
}
