Java read file line by line | Text File | Scanner | Examples

Sometimes we need to Java read file line by line. For example, the text file has data of student roll number and name line by line. So how you will do it? There are many ways to do it in java. In this tutorial, you will learn about Reading file line by line in Java using the scanner class and more ways with examples.

Java read file line by line Text File Scanner Examples

If you are looking only for reading a file then follow this tutorial link – Java Read File Text

Ways to do Java read file line by line

  • BufferedReader
  • Scanner class
  • Using Files
  • RandomAccessFile

Let’s start with Example 

We will see Java read the text file line by line example one by one different method.

The first example, you can look a screenshot of project structure. And Output will be the same for all examples because using the same file.

Java read file line by line example

Read Line using BufferedReader

In BufferedReader use readLine() method to read file line by line to String.  readLine() method returns null at the end of the file. See the below simple example of how to read file line by line with BufferedReader.

Output: First Line
Second Line

Scanner

Here how java read the file line by line scanner example. Open the file and print the content line by line.

Using Files Class

Files class is a utility class that contains various useful methods. A readAllLines method used to read all the file lines into a list of strings.

In an example, it’s a return a list so you need to run a for loop to get the line by line text. See below java read lines from text file example. In the output, you can see the last line is a list.

Output: 1 Line – Java read
2 Line – List data
Read line list [1 Line – Java read, 2 Line – List data]

RandomAccessFile

Use a RandomAccessFile read mode and readLine method to read file line by line.

Question: How to Java Read Text File line by line into Array?

Answer: Using Files Class methods to read text line by line will be a very easy way to do it. Just convert the list to Array as below code.

Complete code

Output: Array [Ljava.lang.String;@3d24753a

Do comment in below if any doubt and suggestions or examples.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java read file line by line are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.