Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a utility method for reading first n lines from file?

Tags:

java

string

file

I have searched the following popular libraries:

  • Guava - Fiels.readLines
  • nio - Files.readFirstLine or Files.readAllLines
  • ApacheCommons - FileUtils.readLines

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?

like image 393
Cherry Avatar asked Jan 30 '26 06:01

Cherry


2 Answers

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()
}
like image 137
Reimeus Avatar answered Jan 31 '26 19:01

Reimeus


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;
    }
}
like image 40
Boris the Spider Avatar answered Jan 31 '26 18:01

Boris the Spider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!