Java file line count


 

Java file line count

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

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

Java file line count

In the 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. In spite of using any IO stream, we have used Scanner class here, 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 data.txt file:

Hello World

All glitters are not gold.
Truth is better than facts.

Here is the code:

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

public class FileLineCount {
	public static void main(String[] args) throws Exception {
		int count = 0;
		File f = new File("C:/data.txt");
		Scanner input = new Scanner(f);
		while (input.hasNextLine()) {
			String line = input.nextLine();
			count++;
		}
		System.out.println("Number of Line: " + count);
	}
}

In this section, we have used data.txt file to read. Output of the above code will display 4 lines as there is a null value between first and third line.

Output:

Number of Line: 4

Ads