Spring boot 读取系统文件几种方法

SpringBoot读取Resource下文件的几种方式

2019.02.15 10:09:51字数396阅读8792

最近在项目中涉及到Excle的导入功能,通常是我们定义完模板供用户下载,用户按照模板填写完后上传;这里模板位置resource/excelTemplate/test.xlsx,尝试了四种读取方式,并且测试了四种读取方式分别的windows开发环境下(IDE中)读取和生产环境(linux下jar包运行读取)。
第一种:

ClassPathResource classPathResource = new ClassPathResource("excleTemplate/test.xlsx");
InputStream inputStream =classPathResource.getInputStream();

第二种:

InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("excleTemplate/test.xlsx");

第三种:

InputStream inputStream = this.getClass().getResourceAsStream("/excleTemplate/test.xlsx");

第四种:

File file = ResourceUtils.getFile("classpath:excleTemplate/test.xlsx");
InputStream inputStream = new FileInputStream(file);

 

Spring Boot默认会将静态资源文件(如txt文件)放在classpath下的/static、/public和/resources目录中,可以直接访问。以下是几种读取txt静态文件方法: 1. 使用ClasspathResourceLoader:在Spring Boot中,可以通过ClasspathResourceLoader类来读取classpath下的文件。可以通过以下代码来读取txt文件: ```java ClassLoader classLoader = getClass().getClassLoader(); Resource resource = new ClassPathResource("static/example.txt"); try { File file = resource.getFile(); // 读取文件内容 } catch (IOException e) { e.printStackTrace(); } ``` 2. 使用ResourceLoader:在Spring Boot中,可以通过ResourceLoader来加载classpath下的文件。可以通过以下代码来读取txt文件: ```java @Autowired private ResourceLoader resourceLoader; public void readTxtFile() { Resource resource = resourceLoader.getResource("classpath:static/example.txt"); try { InputStream inputStream = resource.getInputStream(); // 读取文件内容 inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } ``` 3. 使用文件路径:如果txt文件位于绝对路径下,可以直接使用File类来读取。可以通过以下代码来读取txt文件: ```java String filePath = "/absolute/path/to/example.txt"; File file = new File(filePath); try { BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { // 读取文件内容 } reader.close(); } catch (IOException e) { e.printStackTrace(); } ``` 以上是使用Spring Boot读取txt静态文件几种方法,根据具体情况选择合适的方法来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值