Need to read a text file line by line? 

If so, you'll be happy to learn that the Java NIO package has just what you need to make it easy.

Follow along here for more info.

The File

Let's take a look at a simple flat file. It's called contents.txt and it's located in the root.

And here's what the contents of contents.txt look like:

Now is the time
For all good men
To come to the aid
Of his party

Nice and neat.

Your objective, should you choose to accept it, is to read those contents line by line.

This is the part where you hit your head and say: "Wow. Something so simple and I don't even know how to do it!"

Relax. You're not alone.

I'll help you across the finish line.

Reading the File

You can knock this one out with just a couple of lines of code. Do something like this:

final Path path = Paths.get("./", "contents.txt");
Files.lines(path).forEach(System.err::println);

Run that puppy and it will print out the contents of your flat file in pretty red letters.

So what's going on there? Let me explain it.

The first line creates a Path object. It does that with the aid of the static get() method from the Paths class.

The first parameter in get() is the path to the file. In this case, it's in the root.

The second parameter in get() is the name of the file itself. It's called contents.txt.

In the next line, the code invokes yet another static method: lines() from the Files class.

That's going to return a Stream. Specifically, a Stream of String objects.

Each element in the Stream represents a single line in the file. It's up to you to process the Stream as you see fit.

The code above uses forEach() to iterate over every line and spit it out using System.err because I like System.err because it prints in red.

You'll undoubtedly want to do something much more sophisticated than that. Maybe something like this:

final Path path = Paths.get("./", "contents.txt");
Files.lines(path).forEach(line -> processLine(line));

Then you can handle whatever processing you need to take care of in the processLine() method.

Also note that because Files.lines() gives you a Stream object, you can process it just like you'd handle any other Stream object.

And you've got lots of options with Streams.

Wrapping It Up

That was simple, wasn't it?

Now it's over to you. Read whatever flat files you want line by line with the method I described above.

Have fun!

Photo by Cristian Benavides from Pexels