Java IO - Reading a File from the resources

June 14, 2020 No comments Java IO File Classpath Read Resources

1. Introduction

In this article, we are going to present several ways to read a file from the resources folder in Java. This article covers plain Java solutions and methods dedicated to Spring applications.

2. Read a file from resources using getResourceAsStream method

The most popular solution to read files from the resources folder is to use getResourceAsStream(...) method available in the ClassLoader object.

Let's demonstrate how this solution works using sample Java project with the following structure:

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── frontbackend
    │   │           └── java
    │   │               └── io
    │   │                   └── resources
    │   │                       └── ReadResourcesUsingGetResourceAsStream.java
    │   └── resources
    │       └── example.txt
    └── test
        └── java

Our example.txt file, placed in /src/main/resources folder, has the following content:

This is a sample file in resources folder

Main Java class that reads example.txt file from the resources folder has the following structure:

package com.frontbackend.java.io.resources;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ReadResourcesUsingGetResourceAsStream {

    public static void main(String[] args) throws IOException {
        ReadResourcesUsingGetResourceAsStream obj = new ReadResourcesUsingGetResourceAsStream();

        StringBuilder out = new StringBuilder();
        InputStream inputStream = obj.getClass()
                                     .getClassLoader()
                                     .getResourceAsStream("example.txt");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
        }

        System.out.println(out.toString());
    }
}

In this example we used getClassLoader().getResourceAsStream(...) method available in Class object to load file from resources into byte-based stream.

To print InputStream we used one of the available methods to convert InputStream to String in Java

3. Reading a file from resources folder using getResource method

In the next approach, we used getResource(...) method that returns the URL object for reading the resource, or null if the resource could not be found.

package com.frontbackend.java.io.resources;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;

public class ReadResourcesUsingGetResource {

    public static void main(String[] args) throws IOException {
        ReadResourcesUsingGetResource obj = new ReadResourcesUsingGetResource();

        URL url = obj.getClass()
                     .getClassLoader()
                     .getResource("example.txt");

        File file = new File(url.getFile());
        String content = new String(Files.readAllBytes(file.toPath()));

        System.out.println(content);
    }
}

In this example we make a use of getClassLoader().getResource(...) method to get URL of our example.txt file locate in resources folder. Then we used getFile(...) method to convert URL into File object.

You have many options to read a file in Java. In this example we used Files.readAllBytes(...) method that simply convert InputStream to String in a one line.

4. Read a file from resources in the Spring project using ResourceUtils

ResourceUtils class comes with utility methods for resolving resource locations to files. We can use it to get a file from the resources folder in Spring applications.

In this example we will use Spring project with the following structure:

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── frontbackend
    │   │           └── springboot
    │   │               └── Application.java
    │   └── resources
    │       └── example.txt

Spring boot main class contains a simple REST controller that will return the content of example.txt file from available in the resources folder:

package com.frontbackend.springboot;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Application {

    @GetMapping("/")
    public String getResourceFile() throws IOException {
        File file = ResourceUtils.getFile("classpath:example.txt");
        return new String(Files.readAllBytes(file.toPath()));
    }

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

The application runs on default port 8080. When you enter http://location:8080 address in your browser you will see the content of the example.txt file.

5. Conclusion

In this tutorial, we presented several ways to get a file from the resources folder in Java. In Spring applications we have dedicated utility class that will do all the job for us. In plain Java we need to use getResourceAsStream(...) or getResource(...) method. In many situations, we want to read the file and process it so the natural way is to use the getResourceAsStream(...) approach that returns byte-based stream we can process right away.

{{ message }}

{{ 'Comments are closed.' | trans }}