温馨提示×

java怎么获取resource目录路径

小亿
441
2024-03-01 20:17:14
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中获取resource目录路径有多种方法,具体取决于你的项目结构和资源文件的位置。以下是一些常见的方法:

  1. 使用ClassLoader.getResource()方法:
URL resourceUrl = getClass().getClassLoader().getResource("your/resource/file.txt");
String resourcePath = resourceUrl.getPath();
System.out.println(resourcePath);
  1. 使用Class.getResource()方法:
URL resourceUrl = getClass().getResource("/your/resource/file.txt");
String resourcePath = resourceUrl.getPath();
System.out.println(resourcePath);
  1. 使用System.getProperty()方法获取当前工作目录:
String resourcePath = System.getProperty("user.dir") + "/src/main/resources/your/resource/file.txt";
System.out.println(resourcePath);
  1. 使用File类的相对路径或绝对路径:
File file = new File("src/main/resources/your/resource/file.txt");
String resourcePath = file.getAbsolutePath();
System.out.println(resourcePath);

根据你的项目结构和资源文件的位置选择适合的方法来获取resource目录路径。

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

推荐阅读:java如何获取resource路径

0