Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.IOException;
- import java.io.RandomAccessFile;
- import java.nio.MappedByteBuffer;
- import java.nio.channels.FileChannel;
- public class TestWCJava2 {
- public static void main(String args[]) {
- try {
- new TestWCJava2().run(args);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- void run(String files[]) throws IOException {
- wordCount("/tmp/three"); // hope JIT kicks in here (and hence we exclude timing it later).
- long t0 = System.nanoTime();
- for(String file: files) {
- wordCount(file);
- }
- long t1 = System.nanoTime();
- System.out.println("Elapsed time: " + (t1 - t0) / 1000 + "us");
- }
- int wordCount(String fileName) throws IOException {
- File f = new File(fileName);
- FileChannel fc = new RandomAccessFile(f, "r").getChannel();
- MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
- int nlines = 0;
- byte newline = '\n';
- for(long i = 0; i < fc.size(); i++) {
- if(mem.get() == newline)
- nlines += 1;
- }
- System.out.println(fileName + " lines: " + nlines);
- return nlines;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment