javaでプロジェクトのリソースパスを取得する方法

Javaでは、以下の方法でプロジェクトのリソースパスを取得できます。

  1. getClass().getResource()
URL resourceUrl = getClass().getResource("/path/to/resource/file");
String resourcePath = resourceUrl.getPath();
  1. ClassLoader.getResources()
URL resourceUrl = getClass().getClassLoader().getResource("path/to/resource/file");
String resourcePath = resourceUrl.getPath();
  1. 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 ディレクトリを基準としたリソース・ファイルのパスです。ご自身のファイル構成に合わせて適宜調整してください。

コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds