February 9, 2022

How to Read File in Java

In Java there are various ways to read or write a file, in this post we’ll see some of the ways you can read a file in Java.

Some of the options you have for reading a file in Java are-

  1. Using BufferedReader wrapped around a Reader. See example.
  2. Using Scanner class. See example.
  3. Using methods in java.nio.file.Files class like readAllLines(), newBufferedReader along with lines() method. See example.

To see different options available in Java for writing a file refer this post- How to Write to a File in Java

Using BufferedReader to read file in Java

Using Java BufferedReader class you can read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders.

Java program to read file using BufferedReader

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

  public static void main(String[] args) {
    BufferedReader br = null;
    try{
       String strLine;
       //FileReader instance wrapped in a BufferedReader
       br = new BufferedReader(new FileReader("D:\\test.txt"));
       
       while((strLine = br.readLine()) != null){
         System.out.println(strLine);
       }
    }catch(IOException exp){
      System.out.println("Error while reading file " + exp.getMessage());
    }finally {
      try {
        // Close the stream
        if(br != null){
          br.close();
        }
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
}
Using try-with-resources you can shorten the code you need to write as you won’t be needing finally block in that case to explicitly close the stream. Stream will be closed automatically.

BufferedReader with try-with-resources

public class ReadFile {

  public static void main(String[] args) {
    try(BufferedReader br  = new BufferedReader(new FileReader("D:\\test.txt"))){
      String strLine;
      while((strLine = br.readLine()) != null){
        System.out.println(strLine);
      }
    }catch(IOException exp){
      System.out.println("Error while reading file " + exp.getMessage());
    }
  }
}

Using Scanner to read file

You can also use Scanner class to read file in Java. Scanner class has a constructor where you can pass a File as parameter. Using method nextLine() you can read file line by line where each line is returned as String.

Java program to read file using Scanner

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
  public static void main(String[] args) {
    File file = new File("D:\\test.txt");
    Scanner sc = null;
    try {
      sc = new Scanner(file);
      // Check if there is another line of input
      while(sc.hasNextLine()){
        String str = sc.nextLine();
          System.out.println(str);
      }
    }catch (FileNotFoundException e) {
      System.out.println("Error while trying to read file " + e.getMessage());
    }finally{
      if(sc != null){
        sc.close();
      }
    }
  }		
}

Using Files.readAllLines method to read file

Java 8 onward you can use readAllLines() method of Files class to read a file in Java.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class ReadFile {
  public static void main(String[] args) {
    Path path = Paths.get("D:\\test.txt");
    try {
      List fileList = Files.readAllLines(path);
      System.out.println("" + fileList);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

As you can see readAllLines() method reads the whole file at once and store it into a List which is not a very efficient way of reading a file. Files class provides a better way to read a file using newBufferedReader method.

Using Files.newBufferedReader method to read file

newBufferedReader() method opens a file for reading, returning a BufferedReader to read text from the file in an efficient manner.

Once you have the BufferedReader instance you can use lines() method to read the file line by line. This method returns a Stream, the elements of which are lines read from this BufferedReader. The Stream is lazily populated, i.e., read only occurs during the terminal stream operation.

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFile {
  public static void main(String[] args) {
    Path path = Paths.get("D:\\test.txt");
    try(BufferedReader br = Files.newBufferedReader(path)){
      Stream stream = br.lines();
      stream.forEach(System.out::println);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Using Files.lines method to read file

Files class also has lines() method that you can use to read a file in Java.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFile {
  public static void main(String[] args) {
    Path path = Paths.get("D:\\test.txt");
    // Using Lines method
    try(Stream stream = Files.lines(path)){
      stream.forEach(System.out::println);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

That's all for the topic How to Read File in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment