栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring:DefaultResourceLoader使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring:DefaultResourceLoader使用

Spring:DefaultResourceLoader使用

1 前言

spring的DefaultResourceLoader类实现了ResourceLoader接口,可以方便读取resources等目录下的资源文件,存在于spring-core依赖中。

其他依赖如下:



    commons-io
    commons-io
    2.11.0

2 使用

resources的Demo目录下准备测试test.json文件:

该包下,FileUtils.readFileToString方法可将File文件转换成String,其中需要设置字符集:

package com.xiaoxu.utils.File;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;


public class FileUtils {
    public static String parseJsonFileToString(String caseJsonFilePath){
        DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
        Resource resource = defaultResourceLoader.getResource("classpath:" + caseJsonFilePath);
        File file;
        try {
            file = resource.getFile();
        } catch (IOException e) {
            throw new RuntimeException(String.format("调用%s方法失败,文件获取失败",
                    Thread.currentThread().getStackTrace()[1].getMethodName()));
        }
        String s;
        try {
            s = org.apache.commons.io.FileUtils.readFileToString(file, "utf-8");
        } catch (IOException e) {
            throw new RuntimeException(String.format("调用%s方法失败,String获取失败,%s",
                    Thread.currentThread().getStackTrace()[1].getMethodName(),e.getMessage()));
        }
        return s;
    }

    public static void main(String[] args) {
        System.out.println(parseJsonFileToString("Demo/test.json"));
    }
}

执行结果如下,亦可结合fastjson使用:

{
  "data": [
    {"name": "你好","age": 30}
  ]
}

查看DefaultResourceLoader源码可知,getResource方法读取路径时,开头为classpath:的,会使用ClassPathResource类处理:
并且会截掉classpath:,

    public Resource getResource(String location) {
        Assert.notNull(location, "Location must not be null");
        Iterator var2 = this.getProtocolResolvers().iterator();

        Resource resource;
        do {
            if (!var2.hasNext()) {
                if (location.startsWith("/")) {
                    return this.getResourceByPath(location);
                }

                if (location.startsWith("classpath:")) {
                    return new ClassPathResource(location.substring("classpath:".length()), this.getClassLoader());
                }

                try {
                    URL url = new URL(location);
                    return (Resource)(ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
                } catch (MalformedURLException var5) {
                    return this.getResourceByPath(location);
                }
            }

            ProtocolResolver protocolResolver = (ProtocolResolver)var2.next();
            resource = protocolResolver.resolve(location, this);
        } while(resource == null);

        return resource;
    }

在ClassPathResource类中,还调用了Spring的工具类StringUtils的cleanPath方法将 换成/,还有去掉开头的/等等:

public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
    Assert.notNull(path, "Path must not be null");
    String pathToUse = StringUtils.cleanPath(path);
    if (pathToUse.startsWith("/")) {
        pathToUse = pathToUse.substring(1);
    }

    this.path = pathToUse;
    this.classLoader = classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader();
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/841877.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号