springboot解析resource中的json

19 篇文章 0 订阅
15 篇文章 0 订阅

通常由两种方法
1.方法一

        try {
            // 根据resource文件路径,生成文件
            File jsonFile = ResourceUtils.getFile("classpath:ZhongLv.json");
            // 解析文件为指定编码的字符串
            // 方法实现:先将文件转inPutStream,再调用下面的IOUtils.toString()方法;
            String json = FileUtils.readFileToString(jsonFile,"UTF-8");
            JSONArray jsonArray = JSON.parseArray(json);
        } catch (IOException e) {
            e.printStackTrace();
        }

2.方法二

    /**
     * 本系统和第三方系统字段对应关系json
     */
    @Value("classpath:ZhongLv.json")
    private Resource relation;
 

       String relationStr = null;
        try {
            // 方法实现:将文件的InputStream写入inputStreamReader,再调用方法把reader写入writer,再使用StringBuilderWriter接收,最后toString();
            relationStr = IOUtils.toString(relation.getInputStream(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
        }

3.总结
他们的底层都是IO操作,汇总后的IOUtils.toString方法如下

    private static final int EOF = -1;
    private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
    public static String toString(InputStream input, Charset encoding) throws IOException {

        StringBuilderWriter sw = new StringBuilderWriter();
        InputStreamReader in = new InputStreamReader(input, Charsets.toCharset(encoding));
        char [] buffer = new char[DEFAULT_BUFFER_SIZE];
        long count = 0;
        int n = 0;
        while (EOF != (n = in.read(buffer))) {
            sw.write(buffer, 0, n);
            count += n;
        }
        return sw.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值