Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 414
vhora Avatar asked Dec 21 '16 07:12

vhora


People also ask

How do I remove the first line from a text file in Java?

Scanner fileScanner = new Scanner(myFile); fileScanner. nextLine(); This will return the first line of text from the file and discard it because you don't store it anywhere.

What is the easiest way to read text files line by line in Java 8?

Java 8 has added a new method called lines() in the Files class which can be used to read a file line by line in Java. The beauty of this method is that it reads all lines from a file as Stream of String, which is populated lazily as the stream is consumed.


2 Answers

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!

like image 85
anacron Avatar answered Oct 22 '22 22:10

anacron


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
}
like image 32
Sharon Ben Asher Avatar answered Oct 02 '22 17:10

Sharon Ben Asher