Spring boot 读取静态文件

本文探讨了在不同环境下加载静态资源的方法,特别是在Linux系统中使用Java进行资源文件读取的两种常见方式,包括使用ResourceUtils和ClassPathResource。这些方法对于解决跨平台资源加载问题具有实际意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


1、File jsFileName = ResourceUtils.getFile("classpath:static/js/jsCode.js");//这种方法在linux(未测试)下无法工作
 

2、Resource resource = new ClassPathResource("static/js/jsCode.js");
   File jsFileName =  resource.getFile();
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、付费专栏及课程。

余额充值