溫馨提示×

java怎么獲取項目resource路徑

小億
172
2023-09-20 18:12:30
欄目: 編程語言

在Java中,可以通過以下方式獲取項目的資源路徑:

  1. 使用getClass().getResource()方法:
URL resourceUrl = getClass().getResource("/path/to/resource/file");
String resourcePath = resourceUrl.getPath();
  1. 使用ClassLoader.getResource()方法:
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目錄的路徑。請根據(jù)自己的文件結(jié)構(gòu)進行相應(yīng)的調(diào)整。

0