Write a Java Program to Count number of lines present in the file

Java Program to Count number of lines present in the file

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Count number of lines present in the file
Java Program to Count number of lines present in the file

Write a Java Program to Count number of lines present in the file

PROGRAM: Java Program to Count number of lines present in the file

/*Java Program to Count number of lines present in the file*/

1: Java program to count the number of lines in a file using 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 an object of Scanner
// associated with the file
Scanner sc = new Scanner(file);

// read each line and
// count number of lines
while(sc.hasNextLine()) {
sc.nextLine();
count++;
}
System.out.println(“Total Number of Lines: ” + count);

// close scanner
sc.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}

2: Java program to count the number of lines in a file using java.nio.file package

import java.nio.file.*;

class Main {
public static void main(String[] args) {

try {

// make a connection to the file
Path file = Paths.get(“input.txt”);

// read all lines of the file
long count = Files.lines(file).count();
System.out.println(“Total Lines: ” + count);

} catch (Exception e) {
e.getStackTrace();
}
}
}

Leave a Reply

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