javaでプロジェクトのリソースパスを取得する方法
Javaでは、以下の方法でプロジェクトのリソースパスを取得できます。
- getClass().getResource()
URL resourceUrl = getClass().getResource("/path/to/resource/file");
String resourcePath = resourceUrl.getPath();
- ClassLoader.getResources()
URL resourceUrl = getClass().getClassLoader().getResource("path/to/resource/file");
String resourcePath = resourceUrl.getPath();
- Thread.currentThread().getContextClassLoader().getResource()
URL resourceUrl = Thread.currentThread().getContextClassLoader().getResource("path/to/resource/file");
String resourcePath = resourceUrl.getPath();
「/path/to/resource/file」は、src/main/resources ディレクトリを基準としたリソース・ファイルのパスです。ご自身のファイル構成に合わせて適宜調整してください。