In this tutorial, you will learn how to get the number of lines from a text File in Java.
Create a text file
Create a file named data.txt under the root directory. Next, copy and paste the following text content into the file.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.
All the examples that you will learn in this tutorial will use this text file. The text file contains 10
lines of random text. As a result, the example should display the value 10
to ensure it is working as expected.
Using BufferedReader
Copy and paste the following code into the Main.java file.
package com.javawhizz; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) { int fileLines = 0; try(BufferedReader bufferedReader = new BufferedReader(new FileReader("data.txt"));) { while (bufferedReader.readLine() != null) fileLines++; System.out.println(fileLines); }catch (IOException e){ e.printStackTrace(); } } }
BufferedReader
reads text from an input stream. Any argument of BufferedReader
should be an implementation of the Reader
class. Since FileReader
implements the Reader
class, you can pass it to BufferedReader
.
To read data from a file, you should create an instance of FileReader
and pass it to the BufferedReader
. To get the number of lines in the file, use the readLine()
method of BufferedReader
in a while loop.
As the method reads the lines, increment the counter until the method returns null. As a result, the counter will have the total number of lines after while loop terminates.
Output
10
Using Files.lines() method
Copy and paste the following code into the Main.java file.
package com.javawhizz; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.stream.Stream; public class Main { public static void main(String[] args) { try (Stream<String> stringStream = Files.lines(Path.of("data.txt"));){ System.out.println(stringStream.count()); }catch (IOException e){ e.printStackTrace(); } } }
The Files
class provides static methods to work with files and directories. When it comes to reading lines from a text file, you can leverage the lines()
method.
This method reads all lines from a file as a Stream
. As a result, having access to the Stream API allows you to perform operations on the Stream.
In this case, you only need to call the count()
method on the Stream to get the number of lines in the file.
Output
10
Using LineNumberReader class
Copy and paste the following code into the Main.java file.
package com.javawhizz; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; public class Main { public static void main(String[] args) { try (LineNumberReader lineNumberReader = new LineNumberReader( new FileReader("data.txt"));){ while (lineNumberReader.readLine() != null) System.out.println(lineNumberReader.getLineNumber()); }catch (IOException e){ e.printStackTrace(); } } }
LineNumberReader
class uses a buffer to keep track of line numbers. This means that this example is identical to the first one.
The only difference is that it keeps track of the current line number. This line number increments for every line terminator in the file.
In this case, use the readLine()
method to read the lines in the file. Once the loop terminates, call the getLineNumber()
. This method keeps track of the current line number.
As a result, the method will return the current line numbers from the first line up to the last line.
Output
1 2 3 4 5 6 7 8 9 10
Using Files.readAllLines() method
Copy and paste the following code into the Main.java file.
package com.javawhizz; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class Main { public static void main(String[] args) { try { List<String> strings = Files.readAllLines(Paths.get("data.txt")); System.out.println(strings.size()); }catch (IOException e){ e.printStackTrace(); } } }
This is another static method of the Files
class that reads all the lines from a file. The method name is quite descriptive.
This method expects a Path
object which specifies the location of a file to read text data from. Note that the method returns a List of String elements.
As a result, you only need to call the size()
method of the list class to get the number of lines in the file.
Output
10
Conclusion
In this tutorial, you have learned how to get the number of lines from a text file in Java. In summary, use the BufferedReader
class, Files.lines()
method, LineNumberReader
class, or Files.readAllLines()
method.
0 Comments