几种获取resources目录下的文件方式

前言

一般我们的配置信息默认都是会配置在/src/main/resources/application.properties(或者application.yml)文件中,当然,也可以在resources文件夹下添加自己的配置文件,甚至子目录中添加自己的配置文件,那么我们又该如何读取自己添加的配置文件中的内容呢?

准备

我们先定义一个公共的输出配置信息的方法如下:

privatestaticvoidgetProperties(InputStream inputStream){Properties properties =newProperties();if(inputStream ==null){return;}try{
            properties.load(inputStream);
            properties.list(System.out);}catch(Exception ex){
            ex.printStackTrace();}finally{try{
                inputStream.close();}catch(IOException e){
                e.printStackTrace();}}}

这里是通过java.util下的Properties类来获取配置文件中的属性

添加自定义的配置文件,在resources目录下添加子目录config并添加配置文件db.properties

在java中,resources文件夹下的文件在编译后,都是为根目录(classpath)。接下来,准备采用以下的6种方式进行配置内容的读取

六种方式

方法一

URL path =this.getClass().getClassLoader().getResource("config/db.properties");// 注意路径不带/开头getProperties(path.openStream());

方法二

URL path =this.getClass().getResource("/config/db.properties");//路径需要以/开头getProperties(path.openStream());

方法三

在springboot项目我还可以使用如下的方式:

InputStream inputStream =this.getClass().getClassLoader().getResourceAsStream("config/db.properties");//与方法一类似,只不过直接返回了InputStream类型getProperties(inputStream);

方法四

springboot项目中使用

inputStream =this.getClass().getResourceAsStream("/config/db.properties");//与方法二类似,只不过返回了InputStream类型了getProperties(inputStream);

方法五

springboot项目中使用

ClassPathResource classPathResource =newClassPathResource("config/db.properties");
getProperties(classPathResource.getInputStream());

方法六

springboot项目中使用,通过@Value注解,但是我们还需要通过@PropertySource("classpath:config/db.properties")

注解指定配置文件的路径,如果是默认的配置文件,如:application.properties(.yml)就不需要指定路径

@SpringBootApplication
@PropertySource("classpath:config/db.properties")
publicclassAppimplementsCommandLineRunner{...}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值