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
🌐
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 - @Test public void whenUsingNIOFilesReadAllLines_thenReturnTotalNumberOfLines() throws IOException { List<String> fileStream = Files.readAllLines(Paths.get(INPUT_FILE_NAME)); int noOfLines = fileStream.size(); assertEquals(NO_OF_LINES, noOfLines); } Now let’s check FileChannel, a high-performance Java NIO alternative to read the number of lines:
Discussions

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
Split a text and write different lines in different text file - Oracle Forums
Hello, I am new in java, I am working on a project, but I will start with a simple question (I hope it is simple, cause for me is not). How do I split a text and write each line in a different text fi... More on forums.oracle.com
🌐 forums.oracle.com
October 17, 2023
Linux count number of lines a specific word occurs in a text file based on certain date and time stamp - Unix & Linux Stack Exchange
How can i count number of lines having the word -> [com.java.Name abc] <- in a text file based on certain date and time More on unix.stackexchange.com
🌐 unix.stackexchange.com
June 15, 2020
performance tuning - Determine the Number of Lines in a Text File - Mathematica Stack Exchange
I have looked and looked but I do not see a simple efficient way to get Mathematica to return the number of lines in a text file? I thought about reading the file until it returned the EOF marker,... More on mathematica.stackexchange.com
🌐 mathematica.stackexchange.com
April 17, 2013
🌐
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 - In Java, we can use the NIO `File.lines` and `count()` to get the total number of 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 - It then reads through the file line by line, incrementing the lines counter for each line read until all lines have been processed. Always use a try-with-resources statement to handle AutoCloseable objects like FileReader and BufferedReader. Catch and handle potential IOExceptions that can occur during file operations. This approach is memory-efficient, making it ideal for reading large files that would not fit into memory. Import Java's NIO package components, including Path and Files.
🌐
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
🌐
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.
Find elsewhere
🌐
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 ... scanner sc.close(); } catch (Exception e) { e.getStackTrace(); } } } In the above example, we have used the nextLine() method of the Scanner class to access each...
🌐
Coderanch
coderanch.com › t › 716063 › java › Count-number-characters-words-lines
Count the number of characters, words, and lines in a file (Beginning Java forum at Coderanch)
September 9, 2019 - Your specs say file names is passed on the command line, so you'll need to remove the Scanner based on System.in. Also, your specs are incomplete. How are we to know you can't use String#split()? What else haven't you told us? JavaRanch-FAQ HowToAskQuestionsOnJavaRanch UseCodeTags DontWriteLongLines ItDoesntWorkIsUseLess FormatCode JavaIndenter SSCCE API-17 JLS JavaLanguageSpecification MainIsAPain KeyboardUtility
🌐
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
🌐
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 (Stream<String> fileStream = Files.lines(Paths.get(fileName))) { //Lines count noOfLines = (int) fileStream.count(); } The LineNumberReader is an input stream reader that keeps track of line ...
🌐
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 ...
🌐
Oracle
forums.oracle.com › ords › apexds › post › split-a-text-and-write-different-lines-in-different-text-fi-0248
Split a text and write different lines in different text file - Oracle Forums
October 17, 2023 - Hello, I am new in java, I am working on a project, but I will start with a simple question (I hope it is simple, cause for me is not). How do I split a text and write each line in a different text fi...
🌐
Quora
quora.com › How-many-lines-of-code-do-you-worry-about-the-size-of-a-Java-class
How many lines of code do you worry about the size of a Java class? - Quora
Answer (1 of 5): As others have mentioned, it is not about lines of code. Lines of code can be used as a heuristic though. You should worry in the first place about correctness. In order to achieve correctness, you have to test your code. (I recommend to follow the testing pyramid) In order to...
🌐
Coderanch
coderanch.com › t › 393560 › java › Counting-blank-lines-file
Counting blank lines in a file (Beginning Java forum at Coderanch)
April 5, 2003 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... I have a very simple code snippet which is counting the number of lines in a text file by sequentially reading the lines a BufferedReader and incrementing a counter.
🌐
YouTube
youtube.com › netstrikers - aaditya dubey
Java Programming Tutorial 40 - Calculate the Number of Lines in a File - YouTube
Java Programming Tutorial 40 - Calculate the Number of Lines in a File
Published   July 24, 2014
Views   3K
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-read-file-line-by-line
Java Read File: Complete Guide with Examples | DigitalOcean
February 20, 2025 - The most common way to read a file line by line in Java is by using BufferedReader.
🌐
Ataccama
docs.ataccama.com › runtime-server › latest › workflow-and-scheduler-reference › count-lines-in-text-file.html
Count Lines in Text File :: ONE Runtime Server
Counts lines in a text file. Writes the line count into the task log and stores it into the following task variables: TOTAL_LINE_COUNT: Total number of lines.
Top answer
1 of 2
2

The -c grep option already does the count. So the result of the grep is a single number. Hence wc will of course only find one line. Just remove the wc altogether.

2 of 2
1

The problem with your approach is that you are looking for a pattern which contains [ and ]. These have a special meaning in regular expressions, namely they are "character lists" and match any character enclosed in them. So, performing

grep '[com.java.Name abc]' logfile

would match any line containing any of the characters a, b, c, e, j, m, o, v, N, the space, and the period ., regardless of their location on the line (which likely matches every line of the log file).

You need to escape the [ and ], as in

grep -c '\[com.java.Name abc\]' logfile

or - as pointed out by @terdon - use the -F flag:

grep -c -F '[com.java.Name abc]' logfile

If you want to look for occurences at a certain date, the mechanism depends. If you know the day, say 2020-06-14, it could be as easy as stating

grep -c '^2020-06-14.*\[com.java.Name abc\]' logfile

If you want to search based on the full timestamp, that approach would only work if you knew the exact moment as it is formatted in the logfile, as in

grep -c '^2020-06-14 13:48:12,442.*\[com.java.Name abc\]' logfile

which is unlikely because then you probably wouldn't need to count the occurences in the first place. In that case, you could try to adapt some of the following answers:

  • Extracting between specific time lines from log file with grep and awk
  • grep particular log entry greater than specific time