There's a huge data file. Sometimes you need to know how many lines of these data files are Until now, I've been reading this line by line, but I wonder if there's a way to read it more efficiently.
java large-files line-numbers
When tested, it is 6 times faster than readLine. If it is a 150 megabyte log file, it will read in 0.35 seconds. It takes 2.40 seconds to readLines().
public static int countLines(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return (count == 0 && !empty) ? 1 : count;
} } finally {
is.close();
}
}
© 2024 OneMinuteCode. All rights reserved.