Java file number of lines


 

Java file number of lines

In this section, you will learn how to count the number of lines from the given file.

In this section, you will learn how to count the number of lines from the given file.

Java file number of lines

In this section, you will learn how to count the number of lines from the given file.

Description of code:

Java has provide various useful tools in every aspect. One of them is the Scanner class which is a member of java.util.* package. Here we have used Scanner class to read  all the lines from the file.

You can see in the given example, we have created an object of Scanner class and pass object of File class into the constructor of Scanner class. The method hasNextLine() checks if the file contains next line and the method nextLine() read the line of the string till the end of the file. We have used counter here to detect the number of lines occurred in the file.

 hasNextLine(): This method of Scanner class returns true if there is another line in the input of the Scanner class.

Here is the file.txt file:

Hello

Where there is will, there is a way

Here is the code:

import java.io.*;
import java.util.*;

public class FileCountLine {
	public static void main(String[] args) throws Exception {
		File file = new File("C:/data.txt");
		Scanner scanner = new Scanner(file);
		int count = 0;
		while (scanner.hasNextLine()) {
			String line = scanner.nextLine();
			count++;
		}
		System.out.println("Lines in the file: " + count);
	}
}

In this section, we have used file.txt file to read. Output of the above code will display '3'. It will count the null value too.

 Output:

Lines in the file: 3

Ads