Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Number of lines in a file in Java

By: a guest on Feb 26th, 2012  |  syntax: None  |  size: 1.21 KB  |  views: 19  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. public int count(String filename) throws IOException {
  2.     InputStream is = new BufferedInputStream(new FileInputStream(filename));
  3.     try {
  4.         byte[] c = new byte[1024];
  5.         int count = 0;
  6.         int readChars = 0;
  7.         while ((readChars = is.read(c)) != -1) {
  8.             for (int i = 0; i < readChars; ++i) {
  9.                 if (c[i] == 'n')
  10.                     ++count;
  11.             }
  12.         }
  13.         return count;
  14.     } finally {
  15.         is.close();
  16.     }
  17. }
  18.        
  19. LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));
  20. lnr.skip(Long.MAX_VALUE);
  21. System.out.println(lnr.getLineNumber());
  22.        
  23. public int countLines(String filename) throws IOException {
  24.     LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
  25. int cnt = 0;
  26. String lineRead = "";
  27. while ((lineRead = reader.readLine()) != null) {}
  28.  
  29. cnt = reader.getLineNumber();
  30. reader.close();
  31. return cnt;
  32. }
  33.        
  34. public int countLines(String filename) throws IOException {
  35.     LineNumberReader reader  = new LineNumberReader(new FileReader(filename));
  36.     int cnt = 0;
  37.     String lineRead = "";
  38.     while ((lineRead = reader.readLine()) != null) {}
  39.  
  40.     cnt = reader.getLineNumber();
  41.     reader.close();
  42.     return cnt;
  43. }