English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Arrays

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/)

Java Reader/Writer

Java other topics

Java program calculates the number of lines existing in a file

Java Examples Comprehensive

In this example, we will learn to calculate the number of lines existing in a Java file.

Example1Java program to count the number of lines in a file using the Scanner class

import java.io.File;
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    int count = 0;
    try {
      //Create a new file object
      File file = new File("input.txt");
      //Create a Scanner object 
      //Associate with the file
      Scanner sc = new Scanner(file);
      //Read each line, then
      //Count the number of lines
      while(sc.hasNextLine()) {
        sc.nextLine();
        count++;
      }
      count); + catch (Exception e) {
      // Close the scanner
      sc.close();
    }
      e.getStackTrace();
    }
  }
}

In the above example, we used the nextLine() method of the Scanner class to access each line of the file. Here, according to the number of lines in the file input.txt, the program will display the output.

In this case, our file name is input.txt and it contains the following content:

First Line
Second Line
Third Line

Therefore, we will get the output

Total lines: 3

Example2Java programs use the java.nio.file package to count the number of lines in a file

import java.nio.file.*;
class Main {
  public static void main(String[] args) {
    try {
      //Establish a connection with the file
      Path file = Paths.get("input.txt");
      //Read all lines of the file
      long count = Files.lines(file).count();
      count); + catch (Exception e) {
    }
      e.getStackTrace();
    }
  }
}

In the above example,

  • lines() - Read all lines of the file in stream form

  • count() - Return the number of elements in the stream

Here, if the file input.txt contains the following content:

This is an article about Java examples.
These examples calculate the number of lines in the file.
Here, we use the java.nio.file package.

The program will printTotal Number of Lines:3.

Java Examples Comprehensive