spring项目中读取resources下的文件

spring项目中读取resources下的文件

我们都知道,spring项目经过maven打包后,可以打成jar包或可解压的war包
a. war包是需要外置的web容器去运行的,是需要先解压的
b. jar包的项目通常是内置的web容器(比如spring boot项目),运行的时候并不会对jar包进行解压操作

所以以上两种项目,在解析resources下的文件的时候会有些不同

一、war包的项目(采用外置web容器运行)

由于war包的项目在运行之前会被解压,解压后resources下的文件是真实存在在磁盘上的一个文件,
所以可以获取它的File对象和Inputstream流
例:

当前project工程的resouces目录

config.txt文件内容

phone=19198811100
username=yanchuanbin

可以通过spring提供的ResourceUtils工具或ClassPathResource方式进行读取

            //第一种,通过 org.springframework.util.ResourceUtils 工具类
            File file = ResourceUtils.getFile("classpath:config.txt");

            //第二种,通过org.springframework.core.io.ClassPathResource 去进行读取
            ClassPathResource classPathResource =  new ClassPathResource("config.txt");
            File file1 = classPathResource.getFile();
            InputStream inputStream = classPathResource.getInputStream();

二、jar包的项目(采用内嵌的web容器运行)

由于jar包的项目通常是内嵌容器运行的,所以在运行的时候,服务器上并不会存在一个单独的Resource资源文件
这时候通过ClassPathResource的方式去获取,只能获取它的一个inputstream流,并不能获取到它的File对象

代码

            ClassPathResource classPathResource = new ClassPathResource("config.txt");
            Properties properties = new Properties();
            properties.load(classPathResource.getInputStream());
            //通过spring中 PropertiesLoaderUtils 工具类也可以将file或inputstream转成Properties对象
//           Properties properties = PropertiesLoaderUtils.loadProperties(classPathResource);
            //打印显示出来
            properties.list(System.out);

服务器上运行jar项目

java -jar resources-test.jar

输出显示

- listing properties --
phone=19198811100
username=yanchuanbin

说明打成jar包后,能够访问资源文件里面的内容
由于在打成jar包的时候,maven会对project进行编译处理,可能会将resouces的下的静态资源文件打包成乱码
可以配置一个maven-resources-plugin插件对指定的资源文件进行过虑

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <configuration>
         <nonFilteredFileExtensions>
             <nonFilteredFileExtension>txt</nonFilteredFileExtension>
             <nonFilteredFileExtension>config</nonFilteredFileExtension>
             <nonFilteredFileExtension>properties</nonFilteredFileExtension>
         </nonFilteredFileExtensions>
     </configuration>
 </plugin>
posted @ 2021-03-25 15:59  心若向阳花自开  阅读(605)  评论(0编辑  收藏  举报