BufferedReader lines() Method vs Files lines() Method in Java 8

Java I/O package also get some enhancements in java 8. Java I/O package is a regular API in Java that enables java applications to access the File Systems. Now using java 8, we can interface Readers with Streams. In the BufferedReader class a new lines() method has been added in Java 8. We also have new lines() method in Files factory class in Java 8 that will open a stream on that path directly for me. We will see both new method uses through an example.

Let suppose we have a log file from our development environment and I want to find out First line containing INFO keyword in that file and want to print that line.

Example-1) Reading Text Files Using BufferedReader lines() Method

We know try with resources is new syntax in java 7. Basically what we do, we create our reader or input stream as an argument to the try and instead of explicitly closing, this reader of input stream, will be returned and added to my byte code of this java class. This very new cool stuff from Java 7 that we are using here.

A lines() method has been added on the BufferedReader class in Java 8. This new method opens an stream of string for me on that reader and this stream is formed with each lines of file mydev.log. So basically reader.lines() opens an stream on the mydev.log file and every element of that steam is single line of this file. The rest of the code does regular stream operations as it filtered out all the lines keyword containing “INFO” in it. As I want the first line that contain INFO keyword and just printing out that line on the screen.

Example-2) Reading Text Files Using Files.lines() Method

I can do even better using new Path interface in Java 7. By using Paths.get() method, I can just get the Path of particular file in file system by passing different elements of the Path to the that file. This is new simpler way of creating files from file system using Java 7.

I also have new lines() method in Files factory class in Java 8 that will open a stream on that path directly for me. So we can write up our previous example code in new way and as this stream also closeable, I can pass it as an argument to the try with resources java 7 way. As this stream implements AutoCloseable, and it will close the underlying reader that had been created on that file. So the previous example try with resource code from 3 lines, now limited to single line code.

Also see  reading directories entries using Files Factory Class list() and walk() Method, which is introduced In Java 8.

Leave a Reply

Your email address will not be published. Required fields are marked *