Home Tutorial Java Core Files Java file number of lines

 
 

Share on Google+Share on Google+
Java file number of lines
Posted on: May 2, 2006 at 12:00 AM
Advertisement
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
Advertisement

Related Tags for Java file number of lines:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 2, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com