1. Overview
In this programming tutorial, We'll learn today how to read a text file line by line. Java programs are shown for all possible ways to read file contents.
One of the file tutorials, we have already discussed in-depth on How to read large text files efficiently in java.
We will learn different approaches to read file line by line as String and pass this string to a separate method to process it.
Following are the java API class that provides a way to process the files.
BufferedReader
Scanner
Files
RandomAccessFile
2. Reading File line by line using BufferedReader
BufferedReader is java class and reads the file using FileReader. BufferedReader has a method to read a line by line using readLine(). We are running a loop until readLine() methods null. If the value is null means, a reader reached to end of the file.
package com.javaprogramto.w3schools.programs.files;
/**
*
* Java Program To Read A Text File line by line using BufferedReader
*/
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadLineByLineBufferedReader {
public static void main(String[] args) throws IOException {
// Load the file into BufferedReader
BufferedReader reader = new BufferedReader(new FileReader("files/address.json"));
// Read first line
String line = reader.readLine();
// check line has some value.
while (line != null) {
System.out.println(line);
// read next line
line = reader.readLine();
}
// closing the reader.
reader.close();
}
}
Output:
{ "name" : "John Smith",
"sku" : "20223",
"price" : 23.95,
"shipTo" : { "name" : "Jane Smith",
"address" : "123 Maple Street",
"city" : "Pretendville",
"state" : "NY",
"zip" : "12345" },
"billTo" : { "name" : "John Smith",
"address" : "123 Maple Street",
"city" : "Pretendville",
"state" : "NY",
"zip" : "12345" }
}
3. Reading File line by line using Scanner
Java Scanner class is used to read the file from the file system. It needs the file location and that can be supplied using File object with passing the location. Next, Scanner has two methods hasNextLine() and nextLine().
hasNextLine() method to check whether the Scanner has the next line to read. This method returns true if it has value to read else false.
nextLine() method returns a line from the file.
package com.javaprogramto.w3schools.programs.files;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class ReadLineByLineScanner {
public static void main(String[] args) throws IOException {
// Load the file into Scanner using File object.
Scanner scanner = new Scanner(new File("files/address.json"));
// checking scanner has value to read.
while (scanner.hasNextLine()) {
// read next line
String line = scanner.nextLine();
System.out.println(line);
}
// closing the reader.
scanner.close();
}
}
This program prints all lines from the address.json which is similar to the above output.
Note: Always recommended to call hasNextLine() method before invoking the nextLine(). If no line is present in the file and calling nextLine() method will lead to run time exception saying "No line found" as below.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at com.javaprogramto.w3schools.programs.files.ReadLineByLineScanner.main(ReadLineByLineScanner.java:21)
4. Reading File line by line using Files.readAllLines()
Java Files class is introduced in java.nio.file with a method readAllLines() and returns List<String>.
package com.javaprogramto.w3schools.programs.files;
/**
*
* Java Program To Read A Text File line by line using Files.readALlLines()
*/
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ReadLineByLineFiles {
public static void main(String[] args) throws IOException {
List<String> allLines = Files.readAllLines(Paths.get("files/address.json"));
for (String line : allLines) {
System.out.println(line);
}
}
}
5. Reading File line by line using RandomAccessFile
Another class RandomAccessFile which is used with role-based access and good to work in concurrent mode to read the file content.
RandomAccessFile class has a method readLine() which reads a line and returns as a String.
package com.javaprogramto.w3schools.programs.files;
/**
*
* Java Program To Read A Text File line by line using RandomAccessFile.readLine()
*/
import java.io.IOException;
import java.io.RandomAccessFile;
public class ReadLineByLineRandomAccessFile {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("files/address.json", "r");
String str;
while ((str = file.readLine()) != null) {
System.out.println(str);
}
file.close();
}
}
6. Conclusion
In this article, we have seen all the different ways to read a text or json file line by line.
Shown example programs in the following classes.
BufferedReader
Scanner
Files
RandomAccessFile
All programs above produce the same output.
Do you think which method is efficient to read the file? Please tell your answer in the comments and also please post your questions.
0 Comments