Using Java 8 NIO, how can I read a file while skipping the first line or header record?

10.1k Views Asked by At

I am trying to read a large file line by line, in java, using NIO library. But this file also contains headers... try (Stream<String> stream = Files.lines(Paths.get(schemaFileDir+File.separator+schemaFileNm))){ stream.forEach(s->sch.addRow(s.toString(),file_delim)); }

How do i modify this to skip the first line of the file? Any pointers..?

3

There are 3 best solutions below

3
On BEST ANSWER

Use the Stream.skip method to skip the header line.

try (Stream<String> stream = Files.lines(
          Paths.get(
             schemaFileDir+File.separator+schemaFileNm)).skip(1)){
 // ----
}

Hope this helps!

1
On

The question is: why do you want to do that?

My guess is you're reading a CSV file. In that case you soon will run into other problems like how do I distinguish strings from numbers? or How do I handle double-quotes, semicolon or comma within ""?

My suggestion is to avoid all that trouble right from the start by using a CSV reader framework to parse the file.

0
On

You can opt to try using Iterator

Iterator<String> iter = Files.lines(Paths.get(schemaFileDir+File.separator+schemaFileNm)).iterator();
while (iter.hasNext()) {
    iter.next();                  // discard 1st line
    sch.addRow(iter.next().toString(),file_delim);  // process
}