To count the number of lines in a text file in Java, you can use the BufferedReader
class from the Java I/O library.
Here is an example of how you can use the BufferedReader
class to count the number of lines in a text file in Java:
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) { int lines = 0; while (reader.readLine() != null) { lines++; } System.out.println("Number of lines: " + lines); } catch (IOException e) { e.printStackTrace(); }
This code creates a BufferedReader
object to read the text file "file.txt". It then uses a while
loop to read each line of the file using the readLine
method of the BufferedReader
object. For each line read, it increments a counter variable called lines
. When the readLine
method returns null
, which indicates the end of the file, the loop is terminated and the value of the lines
variable is printed to the console.
The BufferedReader
class provides a convenient way to read a text file line by line. It reads the file in chunks and stores the data in a buffer, which allows you to read the file efficiently.
Note that this code uses a try-with-resources statement to ensure that the BufferedReader
object is closed properly after the reading is finished. The BufferedReader
class implements the AutoCloseable
interface, which allows it to be used in a try-with-resources statement.
You will need to import the java.io.BufferedReader
, java.io.FileReader
, and java.io.IOException
classes in your code and make sure that your project has the necessary dependencies to use the Java I/O library.