Java Program to Read a Large Text File Line by Line
As we are well verse with this topic let us put more stress in order to figure out minute differences between them. Here we are supposed to read from a file on the local directory where a text file is present say it be ‘gfg.txt’. Let the content inside the file be as shown below:
Geeks for Geeks.
A computer science portal.
Welcome to this portal.
Hello Geek !!!
Note: Keep a check that prior doing anything first create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs.
Methods:
- Using Scanner class
- Using BufferedReaader class
Method 1: Using Scanner class
Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. Scanner class is used to read the large file line by line. A Scanner breaks its input into tokens, which by default matches the whitespace.
Example
Java
import java.io.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
public class GFG {
public static void main(String[] args)
throws FileNotFoundException
{
String path = "C:\\Users\\HP\\Desktop\\gfg.txt" ;
InputStream is = new FileInputStream(path);
try (Scanner sc = new Scanner(
is, StandardCharsets.UTF_8.name())) {
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
}
}
}
|
Output:
Geeks for Geeks.
A computer science portal.
Welcome to this portal.
Hello Geek !!!
Method 2: Using BufferedReader class
BufferedReader is used to read the file line by line. Basically, BufferedReader() is used for the processing of large files. BufferedReader is very efficient for reading.
Note: Specify the size of the BufferReader or keep that size as a Default size of BufferReader. The default size of BufferReader is 8KB.
Syntax:
BufferedReader in = new BufferedReader(Reader in, int size);
Example:
Java
import java.io.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class GFG {
public static void main(String[] args)
{
String path = "C:\\Users\\HP\\Desktop\\gfg.txt" ;
try (BufferedReader br
= new BufferedReader( new FileReader(path))) {
String str;
while ((str = br.readLine()) != null ) {
System.out.println(br);
}
}
catch (IOException e) {
System.out.println(
"Error while reading a file." );
}
}
}
|
Output:
Geeks for Geeks.
A computer science portal.
Welcome to this portal.
Hello Geek !!!
Last Updated :
26 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...