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

vhora
  • 320
  • 2
  • 16

3 Answers3

25

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!

NoobEditor
  • 15,563
  • 19
  • 81
  • 112
anacron
  • 6,443
  • 2
  • 26
  • 31
  • 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. – vhora Dec 21 '16 at 08:20
  • Thanks for the answer @anacron – vhora Dec 21 '16 at 08:21
  • 1
    @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. – Holger Dec 21 '16 at 09:31
-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
}
Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
-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.

Timothy Truckle
  • 15,071
  • 2
  • 27
  • 51
  • 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!!! :P – vhora Dec 21 '16 at 08:15