Skip to content

Instantly share code, notes, and snippets.

@awwsmm
Last active August 2, 2018 12:48
Show Gist options
  • Save awwsmm/777bb7b7321a2434309775e953ad09b4 to your computer and use it in GitHub Desktop.
Save awwsmm/777bb7b7321a2434309775e953ad09b4 to your computer and use it in GitHub Desktop.
Count the number of lines in a flat text file
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
// NOTE: adapted from http://bit.ly/2LOQwIP
public class CountLines {
// private constructor in utility class
private CountLines(){}
public static int inTextFile (String fileName) {
try (InputStream is = new BufferedInputStream(new FileInputStream(fileName))) {
final int bufferSize = 4096; // 4kB
byte[] c = new byte[bufferSize];
int readChars = is.read(c);
if (readChars == -1) return 0;
int count = 0;
while (readChars == bufferSize) {
for (int ii = 0; ii < bufferSize; )
if (c[ii++] == '\n') ++count;
readChars = is.read(c);
}
while (readChars != -1) {
for (int ii = 0; ii < readChars; ++ii)
if (c[ii] == '\n') ++count;
readChars = is.read(c);
}
return count == 0 ? 1 : count;
} catch (IOException ex) {
System.err.println("Cannot open file.");
return -1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment