java读取资源路径的几种实现方式
更新时间:2025年02月13日 08:49:37 作者:worilb
文章总结了Java读取资源路径的几种方式,并指出了在JUnit测试文件和普通类中读取资源路径的区别,普通类中读取资源路径时,只返回主目录,而JUnit测试文件中可以精确到所在模块
java读取资源路径几种方式

@Test
public void path() throws IOException {
System.out.println("用户当前工作目录"+System.getProperty("user.dir"));
File directory = new File("");
String path2 = directory.getCanonicalPath();
System.out.println("当前工作目录1:"+path2);
String path3 = directory.getAbsolutePath();
System.out.println("当前工作目录2:"+path3);
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
System.out.println("类加载器返回默认路径:"+path);
String path1 = ResourceUtils.getURL("classpath:").getPath();
System.out.println("ResourceUtils返回默认路径:"+path1);
String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println("resourcePath返回默认路径:"+resourcePath);
ClassPathResource classPathResource = new ClassPathResource("excel/xx.xlsx");
System.out.println("ClassPathResource返回资源路径:"+classPathResource.getURL());
URL resource = this.getClass().getClassLoader().getResource("excel/xx.xlsx");
System.out.println("类加载器返回资源路径:"+resource.getPath());
URL url = ResourceUtil.getResource("excel/xx.xlsx");
System.out.println("ResourceUtil返回资源路径:"+url.getPath());
}

注意:
以上是在Junit测试文件中的结果
工作可以精确到所在模块,而普通类里打印是只有主目录没有模块的。
如下:
public static void main(String[] args) throws IOException {
System.out.println("用户当前工作目录"+System.getProperty("user.dir"));
File directory = new File("");
String path2 = directory.getCanonicalPath();
System.out.println("当前工作目录1:"+path2);
String path3 = directory.getAbsolutePath();
System.out.println("当前工作目录2:"+path3);
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
java开发之基于Validator接口的SpringMVC数据校验方式
这篇文章主要介绍了java开发之基于Validator接口的SpringMVC数据校验方式,文中附含详细示例代码,有需要的朋友可以借鉴参考下2021-09-09
Spring MessageSource获取消息不符合预期的问题解决方案
最近我参与的产品要做国际化支持,选择了用Spring MessageSource来实现,这个Spring 框架提供的工具使用很简单,网上有各种教程文章,这里不做赘述,只说一个实际遇到的问题及解决方案,需要的朋友可以参考下2024-01-01
SpringBoot Starter机制及整合tomcat的实现详解
这篇文章主要介绍了SpringBoot Starter机制及整合tomcat的实现,我们知道SpringBoot自己在“后台”帮我们配置了很多原本需要我们手动去的东西,至于这个“后台”是啥,就是Starter机制2022-09-09


最新评论