BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();

Update: To answer the performance-question raised here, I made a measurement. First thing: 20.000 lines are too few, to get the program running for a noticeable time. I created a text-file with 5 million lines. This solution (started with java without parameters like -server or -XX-options) needed around 11 seconds on my box. The same with wc -l (UNIX command-line-tool to count lines), 11 seconds. The solution reading every single character and looking for '\n' needed 104 seconds, 9-10 times as much.

Answer from Mnementh on Stack Overflow
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ java โ€“ count number of lines in a file
Java - Count number of lines in a file - Mkyong.com
July 21, 2020 - Path path = Paths.get(โ€œresponse.txtโ€); long lineCount = Files.lines(path).count() ; System.out.println(lineCount); ... itโ€™s new feature from Java 7, import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; ... ...
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ count-lines-in-file
Java Program to Count number of lines present in the file
import java.io.File; import ... each line and // count number of lines while(sc.hasNextLine()) { sc.nextLine(); count++; } System.out.println("Total Number of Lines: " + count); // close scanner sc.close(); } catch (Exception e) { e.getStackTrace(); } } } In the above example, ...
Discussions

java - How can I get the count of line in a file in an efficient way? - Stack Overflow
I have a big file. It includes approximately 3.000-20.000 lines. How can I get the total count of lines in the file using Java? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Number of lines in a file in Java - Stack Overflow
I use huge data files, sometimes I only need to know the number of lines in these files, usually I open them up and read them line by line until I reach the end of the file I was wondering if ther... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Read a text file and count the number of lines, stop at a specific character
You seem to try to compare String values with == or !=. This approach does not work reliably in Java as it does not actually compare the contents of the Strings. Since String is an object data type it should only be compared using .equals(). For case insensitive comparison, use .equalsIgnoreCase(). See Help on how to compare String values in our wiki. Your post/comment is still visible. There is no action you need to take. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/javahelp
6
0
February 6, 2022
arrays - How to get the number of lines from a text file in java? - Stack Overflow
I'm a novice in Java. I want to find the number of line in a test file so that I can use it for array size. What my initial thought was to create a loop and update an int variable. like this: Scan... More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 5, 2017
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java io โ€บ find the number of lines in a file using java
Find the Number of Lines in a File Using Java | Baeldung
January 8, 2024 - Java 7 introduced many improvements ... whenUsingNIOFiles_thenReturnTotalNumberOfLines() throws IOException { try (Stream<String> fileStream = Files.lines(Paths.get(INPUT_FILE_NAME))) { int noOfLines = (int) fileStream.count(); ...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ count number of lines in java file
How to Get the Count of Line of a File in Java | Delft Stack
March 11, 2025 - The while loop continues until readLine() returns null, indicating the end of the file. For each line read, we increment the lineCount. Finally, we print the total number of lines. This method is straightforward and efficient, making it a preferred choice for many developers. If you are using Java 8 or later, you can take advantage of the Files.lines() method, which offers a more modern approach to counting lines in a file.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ count-number-of-lines-present-in-the-file
Java Program to Count number of lines present in the file | Vultr Docs
December 16, 2024 - In this article, you will learn how to count the number of lines in a file using Java. You will explore different methods, each suited to different scenarios based on file size and application requirements. Discover how to implement each method with detailed examples and understand the best ...
Top answer
1 of 16
252

This is the fastest version I have found so far, about 6 times faster than readLines. On a 150MB log file this takes 0.35 seconds, versus 2.40 seconds when using readLines(). Just for fun, linux' wc -l command takes 0.15 seconds.

public static int countLinesOld(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        int count = 0;
        int readChars = 0;
        boolean empty = true;
        while ((readChars = is.read(c)) != -1) {
            empty = false;
            for (int i = 0; i < readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
        }
        return (count == 0 && !empty) ? 1 : count;
    } finally {
        is.close();
    }
}

EDIT, 9 1/2 years later: I have practically no java experience, but anyways I have tried to benchmark this code against the LineNumberReader solution below since it bothered me that nobody did it. It seems that especially for large files my solution is faster. Although it seems to take a few runs until the optimizer does a decent job. I've played a bit with the code, and have produced a new version that is consistently fastest:

public static int countLinesNew(String filename) throws IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(filename));
    try {
        byte[] c = new byte[1024];
        
        int readChars = is.read(c);
        if (readChars == -1) {
            // bail out if nothing to read
            return 0;
        }
        
        // make it easy for the optimizer to tune this loop
        int count = 0;
        while (readChars == 1024) {
            for (int i=0; i<1024;) {
                if (c[i++] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }
        
        // count remaining characters
        while (readChars != -1) {
            for (int i=0; i<readChars; ++i) {
                if (c[i] == '\n') {
                    ++count;
                }
            }
            readChars = is.read(c);
        }
        
        return count == 0 ? 1 : count;
    } finally {
        is.close();
    }
}

Benchmark resuls for a 1.3GB text file, y axis in seconds. I've performed 100 runs with the same file, and measured each run with System.nanoTime(). You can see that countLinesOld has a few outliers, and countLinesNew has none and while it's only a bit faster, the difference is statistically significant. LineNumberReader is clearly slower.

2 of 16
201

I have implemented another solution to the problem, I found it more efficient in counting rows:

try
(
   FileReader       input = new FileReader("input.txt");
   LineNumberReader count = new LineNumberReader(input);
)
{
   while (count.skip(Long.MAX_VALUE) > 0)
   {
      // Loop just in case the file is > Long.MAX_VALUE or skip() decides to not read the entire file
   }

   result = count.getLineNumber() + 1;                                    // +1 because line index starts at 0
}
Find elsewhere
๐ŸŒ
W3Docs
w3docs.com โ€บ java
Number of lines in a file in Java
int lineCount = 0; try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { while (reader.readLine() != null) { lineCount++; } } catch (IOException e) { // handle exception } System.out.println("Number of lines: " + lineCount); ...
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ i/o โ€บ count number of lines in a file in java
Count Number of Lines in a File in Java
April 21, 2022 - String fileName = "c:/temp"; long noOfLines = -1; try(LineNumberReader lineNumberReader = new LineNumberReader(new FileReader(new File(fileName)))) { lineNumberReader.skip(Long.MAX_VALUE); noOfLines = lineNumberReader.getLineNumber() + 1; } ...
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ read a text file and count the number of lines, stop at a specific character
r/javahelp on Reddit: Read a text file and count the number of lines, stop at a specific character
February 6, 2022 -

Hello,

I am currently doing some coding homework and it's due at midnight and I'm stuck on this issue. I want to be able to count the number of lines in a text file and stop at a specific character. Here is an example of the text file I'll be reading. Technically it will be a .tgf file but this is what .tfg files look like in Notepad.

0
1
2
3
4
#
2 2
1 3
0 4

I want it to count the number of lines until the "#". We're working on creating our own sort of graph API so 0-4 are the vertices and the count should equal 5. "#" is the separator. The numbers below represent the edges in the graph and I also need to count them so the expected output for the number of edges should be 3. I at first thought that .usedelimiter would be what I needed but it has not been useful. Here is what I've tried:

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

public class readGraph{
   public static void main (String[] args) throws FileNotFoundException {
      File file = new File("../graphtest.txt");
      Scanner fileScanner = new Scanner(file);
      int count = 0;
      while ( fileScanner.hasNextLine()){
            count++;
            fileScanner.nextLine();
            if (fileScanner.nextLine() == "#"){
               break;
            }
      }
      System.out.println(count);
   }
}
Top answer
1 of 4
3
You seem to try to compare String values with == or !=. This approach does not work reliably in Java as it does not actually compare the contents of the Strings. Since String is an object data type it should only be compared using .equals(). For case insensitive comparison, use .equalsIgnoreCase(). See Help on how to compare String values in our wiki. Your post/comment is still visible. There is no action you need to take. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 4
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ How-to-count-the-number-of-lines-in-a-text-file-using-Java
How to count the number of lines in a text file using Java?
Now, split the above string into an array of strings using the split() method by passing the regular expression of the new line as a parameter to this method. Now, find the length of the obtained array. import java.io.File; import java.io.FileInputStream; public class NumberOfCharacters { public static void main(String args[]) throws Exception{ File file = new File("data"); FileInputStream fis = new FileInputStream(file); byte[] byteArray = new byte[(int)file.length()]; fis.read(byteArray); String data = new String(byteArray); String[] stringArray = data.split("\r\n"); System.out.println("Number of lines in the file are ::"+stringArray.length); } }
๐ŸŒ
JavaWhizz
javawhizz.com โ€บ home โ€บ blog โ€บ how to get the number of lines from a text file in java
How to get the number of lines from a text File in Java
September 5, 2023 - In this case, you only need to call the count() method on the Stream to get the number of lines in the file. ... Copy and paste the following code into the Main.java file.
๐ŸŒ
Techcrashcourse
techcrashcourse.com โ€บ 2023 โ€บ 01 โ€บ java-program-to-count-number-of-lines-in-file.html
Java Program To Count Number of Lines In The File
In Java, you can count the number of lines present in a file using the BufferedReader class, which reads text from a character-input stream and provides a convenient method called readLine() which reads a line of text. import java.io.BufferedReader; import java.io.FileReader; import ...
๐ŸŒ
Level Up Lunch
leveluplunch.com โ€บ java โ€บ examples โ€บ count-number-of-lines-in-text-file
Count total number of lines in text file | Level Up Lunch
February 24, 2015 - @Test public void count_lines_text_java8() throws IOException, URISyntaxException { long numberOfLines; try (Stream<String> s = Files.lines(Paths.get(fileLocation), Charset.defaultCharset())) { numberOfLines = s.count(); } catch (IOException e) { throw e; } assertEquals(10, numberOfLines); }
๐ŸŒ
Netjstech
netjstech.com โ€บ 2017 โ€บ 02 โ€บ how-to-count-lines-in-file-java-program.html
How to Count Lines in a File in Java | Tech Tutorials
June 13, 2023 - Then you can get the count of lines ... File("F:\\abc.txt"))); // Read file till the end while ((reader.readLine()) != null); System.out.println("Count of lines - " + reader.getLineNumber()); } catch (Exception ex) { ex.printStackTrace(); } finally { if(reader != null){ try { ...
๐ŸŒ
RoseIndia
roseindia.net โ€บ tutorial โ€บ java โ€บ core โ€บ files โ€บ filelinecount.html
Java file line count
... import java.io.*; import ... = new Scanner(f); while (input.hasNextLine()) { String line = input.nextLine(); count++; } System.out.println("Number of Line: " + count); } }...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ java-program-to-count-the-number-of-lines-words-characters-and-paragraphs-in-a-text-file
Java Program to Count the Number of Lines, Words, Characters, and Paragraphs in a Text File - GeeksforGeeks
October 5, 2021 - SecurityException - if a security manager exists and its checkRead method denies read access to the file. This function is present under the java.io.InputStreamReader package. It creates an InputStreamReader that uses the default charset. ... This function is present under the java.io.BufferedReader package. It creates a buffering character-input stream that uses a default-sized input buffer. ... // Java program to count the // number of lines, words, sentences, // characters, and whitespaces in a file import java.io.*; public class Test { public static void main(String[] args) throws IOExcept
๐ŸŒ
JavaMadeSoEasy
javamadesoeasy.com โ€บ 2015 โ€บ 09 โ€บ 2-ways-to-count-number-of-lines-in-file.html
JavaMadeSoEasy.com (JMSE): 2 ways to Count number of lines in file in java
BufferedReader's readLine() method reads whole line and return it in String form, we will keep variable which will be incremented every time a line is read. We will read till end of file. Program 2 to Count number of lines in file using LineNumberReader in java file IO