iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📁

How to Load Files from the Classpath in Java and Spring

に公開

Environment

  • JDK 25
  • Spring Framework 6.2

It will likely work the same way even if the versions are slightly different.

Folder Structure for This Example

In this case, let's assume we want to retrieve files located under src/main/resources.

.
└── src
    └── main
        ├── java
        │   └── ...
        └── resources
            ├── sample1.txt
            └── bar
                └── baz
                    └── sample2.txt

In the Case of Java

Main.java
package foo;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;

public class Main {
    public static void main(String[] args) {
        try (
                InputStream is1 = Main.class.getClassLoader().getResourceAsStream("sample1.txt");
                InputStream is2 = Main.class.getClassLoader().getResourceAsStream("bar/baz/sample2.txt")
        ) {
            // Process using InputStream
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

Note that getResourceAsStream() returns null if the specified file does not exist.

Official Javadoc -> https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Class.html#getResourceAsStream(java.lang.String)

In the Case of Spring

In application.properties, specify the file path by adding the prefix classpath:.

application.properties
sample.file1=classpath:sample1.txt
sample.file2=classpath:bar/baz/sample2.txt

Retrieve the file as a Resource by adding the @Value annotation.

Sample.java
package foo;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;


@Component
public class Sample {
    private final Resource sample1;

    private final Resource sample2;

    public Sample(
            @Value("${sample.file1}") Resource sample1,
            @Value("${sample.file2}") Resource sample2
    ) {
        this.sample1 = sample1;
        this.sample2 = sample2;
    }

    public void read() {
        try (
                InputStream is1 = sample1.getInputStream();
                InputStream is2 = sample2.getInputStream()
        ) {
            // Process using InputStream
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

Spring Official Documentation -> https://docs.spring.io/spring-framework/reference/core/resources.html#resources-as-dependencies

Discussion