一、maven依赖

使用jackson而非fastjson

<dependency>
	<groupId>jakarta.json</groupId>
    <artifactId>jakarta.json-api</artifactId>
    <scope>compile</scope>
    <version>2.0.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <scope>compile</scope>
    <version>2.11.3</version>
</dependency>

二、代码

  • readFile返回Map,只能读取最外层为花括号的json,最外层为数组的json文件无法读取
  • readFileToObject返回Object,能够读取对象和数组两种形式的json。返回结果难以修改
  • readFileToJson返回JsonNode,返回结果易修改,但是不易展示
package com.dreambyday.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * <p> Description:JsonFileUtils</p>
 * <p> CreationTime: 2022/10/29 10:52
 *
 * @author dreambyday
 * @since 1.0
 */
public final class JsonFileUtils {
	private JsonFileUtils(){}

    /**
     * 文件读取责任链头部
     * 先读取包外jar同级目录的json
     * 再读取包内Resource下的json
     *
     */
    private static final AbstractFileReader HEADER;
    static {
        AbstractFileReader systemFileReader = new SystemFileReader();
        ResourceFileReader resourceFileReader = new ResourceFileReader();
        systemFileReader.setNext(resourceFileReader);
        HEADER = systemFileReader;
    }


    /**
     * 应用场景比较单一,只能读取最外层为花括号的json,最外层为数组的json文件无法读取
     * @param path 读取路径
     * @return 读取结果
     * @throws IOException 异常
     */
    public static Map<String,Object> readFile(String path) throws IOException {
        InputStream resourceAsStream = HEADER.readFile(path);

        if (resourceAsStream == null) {
            return null;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(resourceAsStream, Map.class);
        }
    }

    /**
     * 能够读取对象和数组两种形式的json。返回结果难以修改
     * @param path 路径
     * @return 数据
     * @throws IOException 异常
     */
    public static Object readFileToObject(String path) throws IOException {
        InputStream resourceAsStream = HEADER.readFile(path);

        if (resourceAsStream == null) {
            return null;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(resourceAsStream, Object.class);
        }
    }

    /**
     * 返回结果易修改
     */
    public static JsonNode readFileToJson(String path) throws IOException {
        InputStream resourceAsStream = HEADER.readFile(path);

        if (resourceAsStream == null) {
            return null;
        } else {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readTree(getStr(resourceAsStream));
        }
    }

    public static String getStr(InputStream stream){
        try {
            Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8);
            int ch;
            StringBuilder sb = new StringBuilder();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

抽象类,责任链设计模式,先读取jar包外的json文件,再读取Resource下的json文件

package com.dreambyday.http.chain.read;

import java.io.IOException;
import java.io.InputStream;

import lombok.extern.slf4j.Slf4j;

/**
 * <p> Description:AbstractFileReader</p>
 * <p> CreationTime: 2023/1/12 15:50
 *
 * @since 1.0
 */
@Slf4j
public abstract class AbstractFileReader {
    private AbstractFileReader next;

    public void setNext(AbstractFileReader next) {
        this.next = next;
    }

    /**
     * 读取文件
     *
     * @param originalPath 原始路径。在这里是 类名/方法名.json
     * @return inputStream
     * @throws IOException 异常
     */
    public InputStream readFile(String originalPath) throws IOException {
        String path = buildPath(originalPath);
        InputStream inputStream = readByPath(path);
        if (inputStream == null && next != null) {
            return next.readFile(originalPath);
        } else if (inputStream != null) {
            log.info("读取的文件路径为:{}", path);
            return inputStream;
        } else {
            log.warn("{}未找到文件!", originalPath);
            return null;
        }
    }


    protected abstract InputStream readByPath(String path) throws IOException;

    protected abstract String buildPath(String originalPath) throws IOException;


}

Resource的读取方式

package com.dreambyday.http.chain.read;
import java.io.IOException;
import java.io.InputStream;

/**
 * <p> Description:读取resource文件夹下的文件</p>
 * <p> CreationTime: 2023/1/12 11:43
 * <br>Copyright: ©2023 <a href="https://gitee.com/dreambyday/dashboard/projects">https://gitee.com/dreambyday/dashboard/projects</a>
 * <br>Email: <a href="mailto:dreambyday@qq.com">dreambyday@qq.com</a></p>
 *
 * @author dreambyday
 * @since 1.0
 */
public class ResourceFileReader extends AbstractFileReader{
    @Override
    public InputStream readByPath(String path) {
        return ResourceFileReader.class.getResourceAsStream(path);
    }

    @Override
    protected String buildPath(String originalPath) throws IOException {
        return originalPath;
    }
}

Jar包外的json文件

package com.dreambyday.http.chain.read;


import org.apache.commons.io.FileUtils;

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

/**
 * <p> Description:打成jar包后,从外面读取文件</p>
 * <p> CreationTime: 2023/1/12 11:40
 * <br>Copyright: ©2023 <a href="https://gitee.com/dreambyday/dashboard/projects">https://gitee.com/dreambyday/dashboard/projects</a>
 * <br>Email: <a href="mailto:dreambyday@qq.com">dreambyday@qq.com</a></p>
 *
 * @author dreambyday
 * @since 1.0
 */
public class SystemFileReader extends AbstractFileReader{
    @Override
    public InputStream readByPath(String path) throws IOException {
        File file = FileUtils.getFile(path);
        if (file == null || !file.isFile()) {
            return null;
        }
        return FileUtils.openInputStream(file);
    }

    @Override
    protected String buildPath(String originalPath) throws IOException {
        return "." +  originalPath;
    }
}

三、样例

  1. Resource下创建Json文件

在这里插入图片描述

  1. 代码读取
Map<String,Object>  jsonMap = JsonFileUtils.readFile("/elasticsearch/condition/TimeRange.json")
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐