Java项目查找资源文件搜索路径原理简析

一、在用eclipse构建的项目中,根目录下会有.classpath文件中指定classpath路径。

  说明:kind="src"所指的路径就是classpath路径。

 

二、在用idea构建项目中,会在根目录下的.idea/moudles/xxx_main.iml文件中指定classpath路径。

  说明:url所指的路径就是classpath路径。

 

三、Java中获取classpath目录下资源文件的几种方法的区别和联系

  联系:无论哪一种方式获取最后都是统一委派给ClassLoader类加载器来查找。

  

  区别1、this.class.getResource("").getPath()与this.class.getResource("/").getPath()

  说明:Class的getResource方法会根据传入的参数适当处理,当传入空字符串时,会查找到当前类的路径,当以/开头,程序会跳过/查找后面的路径。

  

 区别2、this.class.getResource("").getPath()与this.class.getClassLoader().getResource("").getPath()

 说明:前者会对输入的参数做处理后者会不对参数做处理并且空字符串表示的是classpath的根路径。

四、Springboot在初始化环境时会添加很多监听器,其中ConfigFileApplicationListener监听器会对application.properties中的配置进行加载,该监听器默认的搜索路径有四个是保存在DEFAULT_SEARCH_LOCATIONS属性中。

五、Linux与Windows通用获取资源文件方式  

Windows测试结果:

Main.class.getResource("").getPath() --> /E:/xxx/classpath/out/production/classes/xxx/xxx/classpath/
Main.class.getResource("/application.properties").getPath() --> /E:/xxx/classpath/out/production/resources/application.properties
Thread.currentThread().getContextClassLoader().getResource( "application.properties" ).getPath() --> /E:/xxx/classpath/out/production/resources/application.properties

Linux测试结果:

Main.class.getResource("").getPath() --> file:/home/xxx/classpath.jar!/com/htiiot/classpath/
Main.class.getResource("/application.properties").getPath() --> file:/home/xxx/classpath.jar!/application.properties
Thread.currentThread().getContextClassLoader().getResource( "application.properties" ).getPath() --> file:/home/xxx/classpath.jar!/application.properties

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值