Using Java 8 NIO, how can I read a file while skipping the first line or header record? [duplicate]
Asked Answered
M

3

12

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..?

Mornings answered 21/12, 2016 at 7:54 Comment(0)
S
26

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!

Sadesadella answered 21/12, 2016 at 8:0 Comment(3)
I saw the skip method but this is what was there in the documentation:Returns a stream, consisting of remaining elements of this stream after discarding the first n elements of the stream, which led me to believe that it would skip n elements of every line.Mornings
Thanks for the answer @SadesadellaMornings
@vhora: the documentation of Stream always uses the term “element” as it can’t know whether these elements are “lines”, as in your case. Depending on how you create the stream, the elements can be entirely different things.Zee
L
-1

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
}
Linseed answered 21/12, 2016 at 8:1 Comment(0)
M
-1

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.

Marsh answered 21/12, 2016 at 8:11 Comment(1)
The answer is because I deem it the best way , and I reached to this conclusion only after going through all options, and no I am not reading a csv file , and yes, I am aware of all the pitfalls. But thanks for keeping other noobs aware and vigilant.. Constant Vigilance!!! :PMornings

© 2022 - 2024 — McMap. All rights reserved.