Guest User

Untitled

a guest
Apr 2nd, 2016
315
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.27 KB | None | 0 0
  1.  
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.io.RandomAccessFile;
  5. import java.nio.MappedByteBuffer;
  6. import java.nio.channels.FileChannel;
  7.  
  8. public class TestWCJava2 {
  9.     public static void main(String args[]) {
  10.         try {
  11.             new TestWCJava2().run(args);
  12.         } catch (IOException e) {
  13.             e.printStackTrace();
  14.         }
  15.     }
  16.  
  17.     void run(String files[]) throws IOException {
  18.         wordCount("/tmp/three"); // hope JIT kicks in here (and hence we exclude timing it later).
  19.  
  20.         long t0 = System.nanoTime();
  21.         for(String file: files) {
  22.             wordCount(file);
  23.         }
  24.         long t1 = System.nanoTime();
  25.         System.out.println("Elapsed time: " + (t1 - t0) / 1000 + "us");
  26.     }
  27.  
  28.     int wordCount(String fileName) throws IOException {
  29.         File f = new File(fileName);
  30.         FileChannel fc = new RandomAccessFile(f, "r").getChannel();
  31.         MappedByteBuffer mem = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
  32.  
  33.         int nlines = 0;
  34.         byte newline = '\n';
  35.  
  36.         for(long i = 0; i < fc.size(); i++) {
  37.             if(mem.get() == newline)
  38.                 nlines += 1;
  39.         }
  40.  
  41.         System.out.println(fileName + " lines: " + nlines);
  42.  
  43.         return nlines;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment