Spring Boot 从Json静态文件中读取数据

Spring Boot 从Json静态文件中读取数据

 

加载文件:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
    @Value("classpath:json/demo.json")
    private Resource demo;

 

读取文件

@Slf4j
public class ReadJson {

    @Value("classpath:json/demo.json")
    private Resource demo;
    public JSONObject demo(){
        try {
            String areaData =  IOUtils.toString(demo.getInputStream(), Charset.forName("UTF-8"));
            return (JSONObject)JSON.parse(areaData);
        } catch (IOException e) {
            log.error("",e);
        }
        return null;
    }
}

输出结果:

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
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静态文件的几种方法,根据具体情况选择合适的方法来实现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值