How to Get the Number of Lines on a Java Read File
Sun Microsystems, acquired by Oracle, distributes the Java programming language with an extensive library of classes and methods that greatly enhance Java's basic capabilities. This library, called Java Platform, includes support for operations on files and streams. The Scanner class allows Java code to treat an input stream as a sequence of user-defined tokens (e.g., the words in a sentence, separated by spaces); Scanner parses the input stream and returns the tokens to calling applications. You can use the Scanner class to count the number of lines on a file in your Java code.
Instructions
-
-
1
Import the required classes by including these lines at the beginning of your program:
import java.io.*;
import java.util.*;
-
2
Create an instance of the Scanner class that takes as input the file whose lines you need to count, as in this sample code:
File input = new File("myFile.txt");
Scanner iterate = new Scanner(input);
Replace "myFile.txt" by the name of the input file.
-
-
3
Count the number of lines in the file by using Scanner's built-in support to parse lines in the input file:
int numLines=0;
while(iterate.hasNextLine()) {
String currLine=iterate.nextLine();
numLines++;
}
At the end of the loop, variable "numLines" will contain the number of lines in the input file.
-
1