java 获取类路径下的资源文件

后端 0 582
小小草
小小草 2023年2月19日 19:29 发表
摘要:在用freemarker生成word文档的时候,在本地可以成功获取到类路径下的资源文件。但是打了jar包放在linux系统下启动,无法获取到该文件,导致生成的word文档是个空文档。

一、问题

在用freemarker生成word文档的时候,在本地可以成功获取到类路径下的资源文件。但是打了jar包放在linux系统下启动,无法获取到该文件,导致生成的word文档是个空文档。

二、解决

1、文件存放路径

2、原先代码

  • 第一种
File docxFile = ResourceUtils.getFile("classpath:templates/"+zip);
  • 第二种
File docxFile = new File(WordUtils.class.getClassLoader().getResource(template).getPath());

以上两种在linux系统种没用,只是获取到target下的文件。在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流。jar中如果想要读取classes下的文件,只能使用getResourceAsStream按流的方式读取。

3、解决方案

ClassPathResource resource = new ClassPathResource("templates/附件1.zip" );
//获取流
			InputStream inputStream = resource.getInputStream();
//新建文件
			File docxFile = new File(fileProperties.getInventoryAttachPath()+File.separator+zip);
//复制到新建的文件中去
			IOUtils.copy(inputStream,docxFile);

这时候还是获取不到文件,是因为回去classPath找是否有这个文件,springboot的maven项目中只会加载classPath同级目录的文件,其他的文件需要在pom.xml中配置
因此在pom.xml中配置:

<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			
		</plugins>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
				<excludes>
					<exclude>**/*.xlsx</exclude>
					<exclude>**/*.xls</exclude>
                                     <!--加上要加载的文件-->
					<exclude>**/*.zip</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>false</filtering>
				<includes>
					<include>**/*.xlsx</include>
					<include>**/*.xls</include>
					<include>**/*.zip</include>
				</includes>
			</resource>
		</resources>
	</build>

这样在本地和linux都可以获取到类路径下的文件了

点赞 0 收藏(0)    分享
相关标签: 文件读取,文件加载
问题没解决?让chatGPT帮你作答 智能助手
0 个评论
  • 消灭零评论