0

I have this File :

 Line1.
 Line2.
 Line3.
 Line4.

I want to start reading from the second line (Line2) till the end of the file. How can i do this in Java?

David M. Karr
  • 14,317
  • 20
  • 94
  • 199

1 Answers1

6

If you want to read the file line by line, but skip the first line, I suggest you do

Files.lines(Paths.get("yourfile"))
     .skip(1)
     .forEach(...);

Note that this solution relies on an API that was added in Java 8 (released March last year), so if you haven't upgraded yet, you may want to do so.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    Not sure if a total beginner will understand that this is Java 8, using streams ... and why it maybe doesnt work at all in his older eclipse. I would at least add some explanations. – GhostCat May 08 '15 at 15:32
  • Answer updated. (I usually have future readers in mind when I write my answers, which is why I try to explain "tomorrows" solution.) Right now however, Java 8 has been out for a year, and the fact that he is a beginner tells me that he doesn't have to respect a legacy code base that can't be migrated to Java 8 :-) – aioobe May 08 '15 at 15:36
  • Very nice and clean, much better than what I was thinking of. – J Atkin May 08 '15 at 15:37
  • Never you knew you can do that !! :O nice :) – yahya el fakir May 08 '15 at 15:46
  • Don’t forget to [use `forEachOrdered`, not `forEach`](http://stackoverflow.com/q/28259636/2711488) if you intend to skip the first line rather than any line. – Holger May 08 '15 at 15:46