How to read a large text file line by line using Java?

Here is a sample to explain how to read a String from a File line-by-line

textfile : D:/tmp/nourit.txt

IT Training Center for Java and Web technology. 
Almost the whole Examples are easily implemented, 
so that every student or developers can understand, 
all examples are presented in Web with videos.

First Example with bufferedReader:

package com.nourit.javaIO;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class ReadContentFromFileLineByLine {

  public static void main(String[] args) {
    try {
      File file = new File("D:/tmp/nourit.txt");
      FileReader fileReader = new FileReader(file);
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      System.out.println("-------------- Start Contents of file: ---------------------");
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        //Here you can manipulate the string the way you want
        System.out.println(line);
      }
      fileReader.close();
      System.out.println("-------------- End Contents of file: ---------------------");
    } catch (IOException e) {
      e.printStackTrace();
    }
    
  }
}

Second Example With Scanner:

Scanner basically scans all the text. The while loop is used to traverse through the entire text.
The .hasNextLine() function is a boolean that returns true if there are still more lines in the text. The .nextLine() function gives you an entire line as a String which you can then use the way you want. Try System.out.println(line) to print the text.

package com.nourit.javaIO;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadContentFromFileLineByLineScanner {

  private static Scanner scan;

  public static void main(String[] args) throws FileNotFoundException {
    System.out.println("-------------- Start Contents of file: ---------------------");
    scan = new Scanner(new File("D:/tmp/nourit.txt"));
    while (scan.hasNextLine()) {
      // Here you can manipulate the string the way you want
      System.out.println(scan.nextLine());
    }
    System.out.println("-------------- End Contents of file: ---------------------");
  }
}

Output:

-------------- Start Contents of file: ---------------------
IT Training Center for Java and Web technology. 
Almost the whole Examples are easily implemented, 
so that every student or developers can understand, 
all examples are presented in Web with videos.
-------------- End Contents of file: ---------------------

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*