📁

Java/Springでクラスパス上のファイルを取得する

に公開

環境

  • JDK 25
  • Spring Framework 6.2

たぶん、多少バージョンが違っていても同じように動くと思います。

今回のフォルダ構造

今回はsrc/main/resources配下のファイルを取得したいとします。

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

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")
        ) {
            // InputStreamを使った処理
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

getResourceAsStream()は、指定したファイルが存在しない場合はnullを返すことに注意してください。

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

Springの場合

application.propertiesに、接頭辞classpath:を付けてファイルのパスを指定します。

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

@Valueを付加して Resource として取得します。

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()
        ) {
            // InputStreamを使った処理
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }
}

Spring公式ドキュメント -> https://docs.spring.io/spring-framework/reference/core/resources.html#resources-as-dependencies

Discussion