I have searched the following popular libraries:
All methods read whole file into memory as String collection. But that is not useful for large files with thousands of lines? Is there a simple method call to read the first n lines of a file in any of these libraries?
You could use LineNumberReader
LineNumberReader reader =
new LineNumberReader
(new InputStreamReader(new FileInputStream("/path/to/file"), "UTF-8"));
try{
String line;
while (((line = reader.readLine()) != null) && reader.getLineNumber() <= 10) {
...
}
}finally{
reader.close()
}
With Java 8 you can use Files.lines:
List<String> readFirst(final Path path, final int numLines) throws IOException {
try (final Stream<String> lines = Files.lines(path)) {
return lines.limit(numLines).collect(toList());
}
}
Pre Java 8 you can write something yourself fairly easily:
List<String> readFirst(final Path path, final int numLines) throws IOException {
try (final BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
final List<String> lines = new ArrayList<>(numLines);
int lineNum = 0;
String line;
while ((line = reader.readLine()) != null && lineNum < numLines) {
lines.add(line);
lineNum++;
}
return lines;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With