Tutorial

Java read text file

Published on August 3, 2022
Default avatar

By Pankaj

Java read text file

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

There are many ways to read a text file in java. Let’s look at java read text file different methods one by one.

Java read text file

java read file, java read text file There are many ways to read a text file in java. A text file is made of characters, so we can use Reader classes. There are some utility classes too to read a text file in java.

  1. Java read text file using Files class
  2. Read text file in java using FileReader
  3. Java read text file using BufferedReader
  4. Using Scanner class to read text file in java

Now let’s look at examples showing how to read a text file in java using these classes.

Java read text file using java.nio.file.Files

We can use Files class to read all the contents of a file into a byte array. Files class also has a method to read all lines to a list of string. Files class is introduced in Java 7 and it’s good if you want to load all the file contents. You should use this method only when you are working on small files and you need all the file contents in memory.

String fileName = "/Users/pankaj/source.txt";
Path path = Paths.get(fileName);
byte[] bytes = Files.readAllBytes(path);
List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);

Read text file in java using java.io.FileReader

You can use FileReader to get the BufferedReader and then read files line by line. FileReader doesn’t support encoding and works with the system default encoding, so it’s not a very efficient way of reading a text file in java.

String fileName = "/Users/pankaj/source.txt";
File file = new File(fileName);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null){
    //process the line
    System.out.println(line);
}

Java read text file using java.io.BufferedReader

BufferedReader is good if you want to read file line by line and process on them. It’s good for processing the large file and it supports encoding also. BufferedReader is synchronized, so read operations on a BufferedReader can safely be done from multiple threads. BufferedReader default buffer size is 8KB.

String fileName = "/Users/pankaj/source.txt";
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, cs);
BufferedReader br = new BufferedReader(isr);

String line;
while((line = br.readLine()) != null){
     //process the line
     System.out.println(line);
}
br.close();

Using scanner to read text file in java

If you want to read file line by line or based on some java regular expression, Scanner is the class to use. Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods. The scanner class is not synchronized and hence not thread safe.

Path path = Paths.get(fileName);
Scanner scanner = new Scanner(path);
System.out.println("Read text file using Scanner");
//read line by line
while(scanner.hasNextLine()){
    //process each line
    String line = scanner.nextLine();
    System.out.println(line);
}
scanner.close();

Java Read File Example

Here is the example class showing how to read a text file in java. The example methods are using Scanner, Files, BufferedReader with Encoding support and FileReader.

package com.journaldev.files;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;

public class JavaReadFile {

    public static void main(String[] args) throws IOException {
        String fileName = "/Users/pankaj/source.txt";
        
        //using Java 7 Files class to process small files, get complete file data
        readUsingFiles(fileName);
        
        //using Scanner class for large files, to read line by line
        readUsingScanner(fileName);
        
        //read using BufferedReader, to read line by line
        readUsingBufferedReader(fileName);
        readUsingBufferedReaderJava7(fileName, StandardCharsets.UTF_8);
        readUsingBufferedReader(fileName, StandardCharsets.UTF_8);
        
        //read using FileReader, no encoding support, not efficient
        readUsingFileReader(fileName);
    }

    private static void readUsingFileReader(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println("Reading text file using FileReader");
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        br.close();
        fr.close();
        
    }

    private static void readUsingBufferedReader(String fileName, Charset cs) throws IOException {
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        InputStreamReader isr = new InputStreamReader(fis, cs);
        BufferedReader br = new BufferedReader(isr);
        String line;
        System.out.println("Read text file using InputStreamReader");
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        br.close();
        
    }

    private static void readUsingBufferedReaderJava7(String fileName, Charset cs) throws IOException {
        Path path = Paths.get(fileName);
        BufferedReader br = Files.newBufferedReader(path, cs);
        String line;
        System.out.println("Read text file using BufferedReader Java 7 improvement");
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        br.close();
    }

    private static void readUsingBufferedReader(String fileName) throws IOException {
        File file = new File(fileName);
        FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);
        String line;
        System.out.println("Read text file using BufferedReader");
        while((line = br.readLine()) != null){
            //process the line
            System.out.println(line);
        }
        //close resources
        br.close();
        fr.close();
    }

    private static void readUsingScanner(String fileName) throws IOException {
        Path path = Paths.get(fileName);
        Scanner scanner = new Scanner(path);
        System.out.println("Read text file using Scanner");
        //read line by line
        while(scanner.hasNextLine()){
            //process each line
            String line = scanner.nextLine();
            System.out.println(line);
        }
        scanner.close();
    }

    private static void readUsingFiles(String fileName) throws IOException {
        Path path = Paths.get(fileName);
        //read file to byte array
        byte[] bytes = Files.readAllBytes(path);
        System.out.println("Read text file using Files class");
        //read file to String list
        @SuppressWarnings("unused")
		List<String> allLines = Files.readAllLines(path, StandardCharsets.UTF_8);
        System.out.println(new String(bytes));
    }

}

The choice of using a Scanner or BufferedReader or Files to read file depends on your project requirements. For example, if you are just logging the file, you can use Files and BufferedReader. If you are looking to parse the file based on a delimiter, you should use Scanner class. Before I end this tutorial, I want to mention about RandomAccessFile. We can use this to read text file in java.

RandomAccessFile file = new RandomAccessFile("/Users/pankaj/Downloads/myfile.txt", "r");
String str;

while ((str = file.readLine()) != null) {
	System.out.println(str);
}
file.close();

That’s all for java read text file example programs.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 4, 2020

how can we validate text from a file while tokenizing it and displaying on the console… Can you please give an example.

- Sami

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 29, 2019

    Thank you guys, very clear explanation and sophisticated solution of problem.

    - Peter

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      December 2, 2018

      Hello, how do i save a JavaFX user input through text field and the result label in a text file?

      - zmstudent

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 7, 2018

        In Example under title “Java read text file using java.nio.file.Files” do we really need this line of code “byte[] bytes = Files.readAllBytes(path);”?

        - simer

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          June 15, 2016

          Hi pankaj, Thansk for the tutorial. private static void readUsingFileReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine()) != null){ //process the line System.out.println(line); } br.close(); fr.close(); } private static void readUsingBufferedReader(String fileName) throws IOException { File file = new File(fileName); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while((line = br.readLine()) != null){ //process the line System.out.println(line); } //close resources br.close(); fr.close(); These 2 methods have exactly the same content. What’s the difference ?

          - safdar

            Try DigitalOcean for free

            Click below to sign up and get $200 of credit to try our products over 60 days!

            Sign up

            Join the Tech Talk
            Success! Thank you! Please check your email for further details.

            Please complete your information!

            Get our biweekly newsletter

            Sign up for Infrastructure as a Newsletter.

            Hollie's Hub for Good

            Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

            Become a contributor

            Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

            Welcome to the developer cloud

            DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

            Learn more
            DigitalOcean Cloud Control Panel