Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

counting the number of lines in a text file (java)

Tags:

java

count

lines

Below is how i count the number of lines in a text file. Just wondering is there any other methods of doing this?

while(inputFile.hasNext()) {    
    a++;
    inputFile.nextLine();
}
inputFile.close();

I'm trying to input data into an array, i don't want to read the text file twice.

any help/suggestions is appreciated.

thanks

like image 287
Nghia Avatar asked Dec 07 '22 00:12

Nghia


2 Answers

If you are using java 7 or higher version you can directly read all the lines to a List using readAllLines method. That would be easy

readAllLines

List<String> lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());

Then the size of the list will return you number of lines in the file

int noOfLines = lines.size();
like image 121
Thusitha Thilina Dayaratne Avatar answered Dec 23 '22 11:12

Thusitha Thilina Dayaratne


If you are using Java 8 you can use streams :

long count = Files.lines(Paths.get(filename)).count();

This will have good performances and is really expressive.

The downside (compared to Thusitha Thilina Dayaratn answer) is that you only have the line count. If you also want to have the lines in a List, you can do (still using Java 8 streams) :

// First, read the lines
List<String> lines = Files.lines(Paths.get(filename)).collect(Collectors.toList());
// Then get the line count
long count = lines.size();
like image 34
superbob Avatar answered Dec 23 '22 13:12

superbob