springboot读取目录下的文件

springboot读取resources目录下的文件

记录一次问题

背景:项目中需要做按照固定的Word模板导出,所以我把word模板,放在了resources目录下面。然后,读取这个模板。

本地环境是好的,但是部署测试环境的时候,除了问题。

原本的读取方式:
File file = ResourceUtils.getFile(“classpath:file/shbg.docx”);
测试环境直接报错,经过百度之后改成了:

   ClassPathResource resource = new ClassPathResource("file/shbg.docx");
    InputStream inputStream = null;
    try {
        inputStream = resource.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

获得当前的类加载器,通过类加载器读取文件流。
(或者一下两种方法)
1
InputStream io = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(“test.txt”);

2
InputStream io = getClass().getClassLoader().getResourceAsStream(“test.txt”);

在Spring Boot中,可以使用`ResourceLoader`来加载根目录下的文件。以下是一些常见的方法: 1. 通过`ResourceLoader`加载文件 ```java import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.nio.file.Files; import java.nio.file.Paths; @Component public class MyComponent { private final ResourceLoader resourceLoader; public MyComponent(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } @PostConstruct public void init() throws Exception { Resource resource = resourceLoader.getResource("classpath:myfile.txt"); byte[] contents = Files.readAllBytes(Paths.get(resource.getURI())); System.out.println(new String(contents)); } } ``` 2. 通过`ClassPathResource`加载文件 ```java import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.nio.file.Files; import java.nio.file.Paths; @Component public class MyComponent { @PostConstruct public void init() throws Exception { ClassPathResource resource = new ClassPathResource("myfile.txt"); byte[] contents = Files.readAllBytes(Paths.get(resource.getURI())); System.out.println(new String(contents)); } } ``` 以上代码中,第一个例子是通过`ResourceLoader`加载文件,第二个例子是通过`ClassPathResource`加载文件。注意,文件路径中的`classpath:`前缀表示文件在类路径下。如果文件不在类路径下,可以使用`file:`前缀来指定绝对路径。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值