private static int countLines(String str){
   String[] lines = str.split("\r\n|\r|\n");
   return  lines.length;
}
Answer from Tim Schmelter on Stack Overflow
🌐
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.
Discussions

java - Count chars, words and lines - Code Review Stack Exchange
At first glance, it seems like ... line is indented for not reason. ... You could use Scanner class for more convenience. To handle the case with duplicate whitespaces we could use line.replaceAll("\\s+", " "). import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Counter { public void count(String filename) ... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
March 29, 2017
Count number of lines in a string in java - BufferedReader behavior - Stack Overflow
I am using the function countLines to count the number of lines in a string. It uses StringReader and BufferedReader. But I get a different result than I expected for the string test in my example.... More on stackoverflow.com
🌐 stackoverflow.com
July 4, 2015
count - counting the number of lines in a text file (java) - Stack Overflow
I had to read the text then make an array based on the length of the text. then read the data again and put it into the array. its like 10-15 lines of code alone to just count the text file. ... If you are using java 7 or higher version you can directly read all the lines to a List using ... More on stackoverflow.com
🌐 stackoverflow.com
java - Counting number of lines, words, and characters in a text file - Stack Overflow
I am trying to take input from a user, and print the amount of lines, words, and characters in a text file. However, only the amount of words is correct, it always prints 0 for the lines and chara... More on stackoverflow.com
🌐 stackoverflow.com
May 22, 2017
🌐
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.
🌐
Ispycode
ispycode.com › Blog › java › 2016-07 › How-to-get-line-count-from-a-string
How to get line count from a string | java blog - I Spy Code
Use the String split() method. Here is a java example that shows how to count the number of lines in a string:
🌐
Java2s
java2s.com › example › java-utility-method › string-line-count › countlines-string-what-0fac9.html
Java String Line Count countLines(String what)
co m * Copyright (c) 2010 Ben Fry and Casey Reas * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.opensource.org/licenses/eclipse-1.0.php */ public class Main { /** * Get the number of lines in a file by counting the number of newline * characters inside a String (and adding 1). */ static public int countLines(String what) { int count = 1; for (char c : what.toCharArray()) { if (c == '\n') count++; } return count; } }
🌐
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?
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); } } Number of lines in the file are ::3 · Arushi · Updated on: 2020-02-20T05:15:24+05:30 · 2K+ Views · How to read a file in Java Javaexamples · How to count a group of words in a string using Java Javaexamples ·
🌐
Aviator Dao
java2novice.com › главная страница › welcome to aviator dao from the creators of the java2novice
From Java Programming to Aviator Game: Explore Aviator DAO
July 17, 2024 - Discover the evolution of our journey from Java programming tutorials to the exciting world of the Aviator Game. At Aviator DAO, we provide in-depth guides, strategies, and resources for mastering Aviator.
Top answer
1 of 3
6

Bug

The program doesn't count words correctly, for example in "a text like this", because it counts every whitespace character as a word, without handling consecutive whitespace characters.

Reading character by character is inefficient

Reading a file character by character is not very efficient. It would be better to use a buffered reader and process the file line by line. Here's an example of doing that, which also solves the bug with word counting:

long[] counts = new long[3];
try(InputStream in = new FileInputStream(filename);
    BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")))
) {
    String line;
    while ((line = reader.readLine()) != null) {
        counts[2]++;
        counts[1] += line.split("\\s+").length;
        counts[0] += line.length() + 1;
    }
}
return counts;

This might still not be accurate, and probably there are corner cases where it will not count words correctly, but it's still more accurate than the original.

Encapsulation

The implementation doesn't encapsulate well the results. It returns a long[], which is not great because you have to remember the array indexes that correspond to characters, words, lines, which is error prone. Even if you add constants like CHARS_INDEX = 0, WORDS_INDEX = 1 to eliminate magic numbers, it will not solve the encapsulation problem: users of the function will know too much about the internal implementation, that it uses a long[] for storage. It would be cleaner to create a dedicated CountResult class to encapsulate the results.

For example:

private static class CountResult {
    private final long chars;
    private final long words;
    private final long lines;

    private CountResult(long chars, long words, long lines) {
        this.chars = chars;
        this.words = words;
        this.lines = lines;
    }
}

And then use it like this:

long chars = 0;
long words = 0;
long lines = 0;
while ((line = reader.readLine()) != null) {
    lines++;
    words += line.split("\\s+").length;
    chars += line.length() + 1;
}
return new CountResult(chars, words, lines);

Callers will not need to remember indexes, the counts will be accessible intuitively by names.

Unused variables

You have some unused variables:

Reader buffer = new BufferedReader(reader)

String newLineChar = System.lineSeparator();

It would be better to remove them.

2 of 3
2

In every case of the if statement, the line counts[0]++; is executed. You can extract that outside the if statement and drop the last else block.

counts[0]++;
if(character == '\n') {
     counts[2]++;
     counts[1]++;
 } else if(Character.isWhitespace(character)) {
     counts[1]++;
 }

Having the closing parenthesis of the try clause on it's own line is distracting. At first glance, it seems like it is closing a block and the next line is indented for not reason.

Find elsewhere
🌐
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 whenUsingNIOFiles_thenReturnTotalNumberOfLines() throws IOException { try (Stream<String> fileStream = Files.lines(Paths.get(INPUT_FILE_NAME))) { int noOfLines = (int) fileStream.count(); assertEquals(NO_OF_LINES, noOfLines); } } ... @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:
🌐
Dot Net Perls
dotnetperls.com › line-count-java
Java - Line Count for File - Dot Net Perls
while (true) { String line = reader.readLine(); if (line == null) { break; } lineCount++; } reader.close(); // Display the line count. System.out.println("Line count: " + lineCount); } } ... For a file that is resident in memory, we can use a for-loop and scan for a known newline character.
🌐
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 - The Files.lines() method can be used to get the stream of lines from a specified text file. Then we can use stream.count() method for counting the elements in the stream. Note that the file is closed by closing the stream.
🌐
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 count() method then returns the total number of lines. This approach is not only shorter but also takes advantage of Java’s functional programming features, making it a great choice for modern applications. It also handles large files efficiently, as it processes lines in a lazy manner.
🌐
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 - // 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 IOException { File file = new File("C:\\Users\\hp\\Desktop\\TextReader.txt"); FileInputStream fileInputStream = new FileInputStream(file); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String line; int wordCount = 0; int characterCount = 0; int paraCount = 0; int whiteSpaceCount = 0; int sentenceCount =
🌐
Tutorialspoint
tutorialspoint.com › java › lang › string_lines.htm
Java String lines() Method
In the example given below we are counting the number of lines in the given string using the lines() method followed by the Stream API count() method. Here, stream of lines are extracted using the '\r\n' terminator: import java.util.stream.Stream; ...
🌐
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 line of the file....
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › count-of-lines-required-to-write-the-given-string
Count of lines required to write the given String - GeeksforGeeks
December 13, 2022 - // CPP implementation of the approach #include <bits/stdc++.h> using namespace std; // Function to return the number of lines required pair<int, int> numberOfLines(string S, int *widths) { // If string is empty if (S.empty()) return {0, 0}; // Initialize lines and width int lines = 1, width = 0; // Iterate through S for (auto character : S) { int w = widths[character - 'a']; width += w; if (width >= 10) { lines++; width = w; } } // Return lines and width used return {lines, width}; } // Driver Code int main() { string S = "bbbcccdddaa"; int widths[] = {4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; // Function call to print required answer pair<int, int> ans = numberOfLines(S, widths); cout << ans.first << " " << ans.second << endl; return 0; } // This code is contributed by // sanjeev2552 · Java ·