DEV Community

Cover image for Reading files with Java.
Benjamin Thorpe
Benjamin Thorpe

Posted on

Reading files with Java.

Reading and Writing from & to files are another important part of any programming language.
Without much history, lets learn how to Read files.

Let's assume you want to read a file on your desktop named test.txt and your java program also is on your desktop.
text.txt has the following lines:
"Hello World of Java"
"I am reading a file"

import java.io.*;

class ReadFile{
  public static void main(String[] args){
    File file = new File("text.txt");

    try(FileReader fr = new FileReader(file);
        BufferedReader br = new BufferedReader(fr);){

      String line;
      while((line = br.readLine()) != null){
        System.out.println(line);
      }
    }catch(IOException ioe){
      System.out.println(ioe.getMessage());
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

To run it in the terminal, type

// -> Java 10 and below
javac ReadFile.java
java ReadFile

// -> Java 11 and above (no need to compile it first)
java ReadFile.java 

// output
Hello World of Java
I am reading a file
Enter fullscreen mode Exit fullscreen mode

Time to break it down a little.

File file = new File("text.txt");

// The File class does not create a file, 
// It only holds the location/path of the file.
//eg: 
    File file = new File("path-to-file");
Enter fullscreen mode Exit fullscreen mode
String line;
while((line = br.readLine()) != null)
...

// can also be written as
String line = br.readLine();
while(line != null){
  System.out.println(line);
  line = br.readLine();  // reads the line again
}
Enter fullscreen mode Exit fullscreen mode
try(FileReader fr = new FileReader(file);
    BufferedReader br = new BufferedReader(fr);){
...
Enter fullscreen mode Exit fullscreen mode

This try(...){ closes the FileReader and BufferedReader automatically for us. Read more about try-with-resource in my other post;

Exception Handling with JDK 6 vs JDK 7 and above.

Thanks for reading. Next up, we will learn how to write/create a file.
Please leave your comments and any questions you might have.

Top comments (0)