Over

120,000

Worldwide

Saturday - Sunday CLOSED

Mon - Fri 8.00 - 18.00

Call us

 

Read a file line by line in Java 7 and Java 8

Read a file line by line in Java 7 and Java 8

Scanner, BufferedReader, Files, RandomAccessFile

A file is an object on a computer that stores data, information, settings, or commands used with a computer program. In Java a resource is a piece of data that can be accessed by the code of an application. The files can be crazily large, with gigabytes or terabytes being stored, so reading such files wholly is ineffectual.

When reading files line by line, we have the ability to explore only the significant information and stop the searching as soon as we have what the thing that we were looking for. It also allows to break up the data into logical pieces, for example if it were a CSV-formatted file.

We have different ways to read a file line by line in java. Here we will look each of them.

Scanner

Reading a file line by line in java by using the Scanner class is one of the easiest ways. The Scanner breaks the input into the characters, using a delimiting pattern, which in our case has the character of a new line.

Using the hasNextLine() method checks whether there is another line in the input of the scanner, and returns true if there is, otherwise false. But here the scanner itself does not read the file, and for reading it we should use the nextLine() method.

Because this method continues to search through the input by looking for a line divider, it can buffer all entries when searching for the end of the line if there are no line dividers.

Here is an example of using Scanner class for reading a file and then outputting its lines. public class Example1 {

public static void main(String[] args) throws FileNotFoundException {

readFile();

}

public static void readFile() {

try {

Scanner scanner = new Scanner(new File(“C:/Users/User/myFile.txt”)); while (scanner.hasNextLine()) {

System.out.println(scanner.nextLine());

}

scanner.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

The output will be:

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,

but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the

1960s with the release of Letraset

sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

So we have outputted the content written in that file.

The main advantage of using Scanner for reading file is that it allows you to change delimiter using useDelimiter() method, so you can use any other delimiter like comma, pipe instead of white space. Below is an example of using this method:

public class ScannerDelimiterExample {

public static void main(String[] args) throws FileNotFoundException {

read();

}

public static void read() {

Scanner scanner = null;

try {

scanner = new Scanner(new File(“C:/Users/User/myDoc.txt”));

} catch (FileNotFoundException e) {

e.printStackTrace();

}

if (scanner != null) {

scanner.useDelimiter(“/”);

while (scanner.hasNext()) {

System.out.println(scanner.next());

}

scanner.close();

}

}

}

The file that we use here, has the same content but only there have been added several of ‘/’ character to see its work. The file contains this:

What is/ Lorem Ipsum?

Lorem Ipsum is/ simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry’s standard dummy/ text ever since the 1500s, when an unknown /printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,

but also/ the leap into electronic typesetting, remaining essentially /unchanged. It was popularised in the 1960s with the release of Letraset

sheets containing Lorem Ipsum/ passages, and more recently with desktop publishing software like/ Aldus PageMaker including versions of Lorem Ipsum.

And in the output we will get this result:

What is

Lorem Ipsum?

Lorem Ipsum is

simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry’s standard dummy

text ever since the 1500s,

when an unknown

printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,

but also

the leap into electronic typesetting, remaining essentially

unchanged. It was popularised in the 1960s with the release of Letraset

sheets containing Lorem Ipsum

passages, and more recently with desktop publishing software like

Aldus PageMaker including versions of Lorem Ipsum.

Buffered Reader

We can also use BufferedReader class to read the characters, arrays and also here we can specify the amount of data that is buffered, for performance reasons. By default it is 8192 bytes. BufferedReader br = new BufferedReader(new FileReader(file), bufferSize);

Here we have to use FileReader for an appropriate data source which extends InputStreamReader.

public class Example2 {

public static void main(String[] args) throws IOException {

read();

}

public static void read() throws IOException {

try (BufferedReader reader = new BufferedReader(new FileReader(“C:/Users/User/myFile.txt”))) { String line = reader.readLine();

while (line != null) {

System.out.println(line);

line = reader.readLine();

}

}

}

}

The way that we have initialized the BufferedReader inside the try is using the automatic resource management, which is specific from Java 7 or higher. But for older versions you can write initializing the variable before try block. The example is below:

public class Example3 {

public static void main(String[] args) throws IOException {

read();

}

public static void read() throws IOException {

BufferedReader reader = null;

try {

reader = new BufferedReader(new FileReader(“C:/Users/User/myFile.txt”)); String line = reader.readLine();

while (line != null) {

System.out.println(line);

line = reader.readLine();

}

} finally {

if (reader != null) {

reader.close();

}

}

}

}

And the output of both of these codes will again be the same, the content inside the file: What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,

but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset

sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Files

We can read the files by using Files class starting from Java 8 and using Streams. The Files.lines() is a static helper method which we can initialize in try with try-with-resources syntax. Now we can write a code where we read the lines of the file and get those which and with ‘.’ character. public class Example4 {

public static void main(String[] args) {

read();

}

public static void read() {

Path filePath = Paths.get(“C:/Users/User”, “myFile.txt”);

try (Stream<String> stream = Files.lines(filePath)) {

stream

.filter(s -> s.endsWith(“.”))

.sorted()

.map(String::toUpperCase)

.forEach(System.out::println);

} catch (IOException e) {

e.printStackTrace();

}

}

}

Here by filter() method we get a stream consisting of those elements, which we specify. In the Stream the filter(), sorted() and map() methods’ order can be changed, but the foreach() should always be in the end, as it is void and returns nothing.

This code’s result will be:

SHEETS CONTAINING LOREM IPSUM PASSAGES, AND MORE RECENTLY WITH DESKTOP PUBLISHING SOFTWARE LIKE ALDUS PAGEMAKER INCLUDING VERSIONS OF LOREM IPSUM.

RandomAccessFile

Using RandomAccessFile we open a file in read mode and then use its readLine() method for reading file line by line.

public class Example5 {

public static void main(String[] args) {

read();

}

public static void read() {

try {

RandomAccessFile file = new RandomAccessFile(“C:/Users/User/myFile.txt”, “r”); String str;

while ((str = file.readLine()) != null) {

System.out.println(str);

}

file.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

Here when the end of file is reached before the desired number of byte has been read than EOFException is thrown, which is a type of IOException.

The output is:

What is Lorem Ipsum?

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum has been the industry’s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries,

but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset

sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

RandomAccessFile allows you to read and write a small piece of data at any position in the file, using a file pointer. By controlling this file pointer, you can move forth and back within the file to perform

reading and writing operations, at any position you want, in a random way. Besides this is ideal for low level manipulation of a certain file format, such as reading, creating and updating MP3 files, PDF files, etc and even your own file format.

Here you can see an example of a writing in a file with RandomAccessFile and getting its file pointers and printing them:

public class RandomAccessFileExample {

public static void main(String[] args) {

read();

}

public static void read() {

try {

RandomAccessFile raf = new RandomAccessFile(“C:/Users/User/test.txt”, “rw”); raf.writeUTF(“This is an example of Random access file”);

raf.seek(0);

System.out.println(“” + raf.readUTF());

System.out.println(“” + raf.getFilePointer());

raf.seek(5);

System.out.println(“” + raf.getFilePointer());

raf.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

The output will be:

This is an example of Random access file

42

5

So we saw that we have different ways of reading a file line by line. You might choose it depending on the size of the file, the performance issues, libraries etc.

Leave a Reply

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

Working Hours

  • Monday 9am - 6pm
  • Tuesday 9am - 6pm
  • Wednesday 9am - 6pm
  • Thursday 9am - 6pm
  • Friday 9am - 6pm
  • Saturday Closed
  • Sunday Closed