java怎么获取项目resource路径

1575
2023/10/18 18:12:30
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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目录的路径。请根据自己的文件结构进行相应的调整。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中while如何停止