How to Read a File in Java

There are multiple ways we can read a file in Java. We can always do that using the good old classes such as FileReader, BufferedReader, or Scanner class.

However, in this lesson, we will explore other ways/libraries that make reading a file easier, and we are not required to write a lot of code.

We will cover the following ways:

  • Using the Files.readAllBytes() method
  • Using the Files.lines() method
  • Using the InputStream and IOUtils classes

Read a file in Java using the Files.readAllBytes() method

We have the Files class from the java.nio.file package. This class consists exclusively of static methods that operate on files, directories, or other types of files.

In this example, we will use the readAllBytes() method to read the bytes from a file.

Example

Let’s say we have a file with the name “file1” in src/main/resources folder:

Hello!
Some text here!
Bye!


Now let’s read it using the Files.readAllBytes() method:

class Test {

  public static void main(String[] args) throws IOException {
    String content = new String(Files.readAllBytes(Paths.get("src/main/resources/file1.txt")));

    System.out.println("Content of the file: \n" + content);
  }
}
Output: Content of the file: Hello! Some text here! Bye!
 
And that’s it! See how easy it is to read a file using the readAllBytes() method.
 
Note: we also used the Paths.get() method to convert a path string to a Path.

Read a file in Java using the Files.lines() method

Class Files also contains one useful method lines() that reads all lines from a file. We can use it together with the Java 8 forEachOrdered() method. This is basically a one-liner:

Example

class Test {
  public static void main(String[] args) throws IOException {
    Files.lines(Paths.get("src/main/resources/file1.txt")).forEachOrdered(System.out::println);
  }
}
Output: Hello! Some text here! Bye!

Read a file in Java using the InputStream and IOUtils

We can also use the toString() method from the IOUtils class that belongs to the Apache Commons library. This class provides static utility methods for input/output operations.

Note: You’ll need to add a dependency to your project to use it. You can find it in the Maven repository.

The toString() method accepts an InputStream as the first parameter and the String, which represents a charset name as the second. For this purpose, we don’t need to specify the charset name, so we will leave it null.

Example

class Test {
  public static void main(String[] args) throws IOException {

    try (FileInputStream inputStream = new FileInputStream("src/main/resources/file1.txt")) {
      String content = IOUtils.toString(inputStream, (String) null);
      System.out.println(content);
    }
  }
}
Output: Hello! Some text here! Bye!
 
That was all about how to read a file in Java. 

Happy coding!

Leave a Reply

Your email address will not be published.