spring boot项目运行jar包读取包内resources目录下的文件

spring boot项目运行jar包读取包内resources目录下的文件


摘要

Spring Boot 项目打包成 jar 包后,resources 目录下的文件将会被打包到 jar 包中。如果需要在 Spring Boot 项目运行 jar 包后读取 resources 目录下的文件,可以使用 this.getClass().getResourceAsStream() 方法。

结果输出:

bash 复制代码
jar包程序读取包内resources下的文件:
{"name":"小明","age":45}
{"level":2,"name":"小丽","age":33}

码代码

文件所在目录/src/main/resources/static/my-json-data.json

java 复制代码
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;

@Component
public class MockRunApp {
    static String jsonData1;
    static String jsonData2;

    /**
     * Bean的构建后置过程中读取resources目录下的文件
     */
    @PostConstruct
    public void constructFunc(){
        try {
            InputStream resourceAsStream = this.getClass().getResourceAsStream("/static/my-json-data.json");
            assert resourceAsStream != null;
            String content = IOUtils.toString(resourceAsStream, "UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            Object object = objectMapper.readValue(content, Object.class);
            JSONArray objects = JSON.parseArray(JSONObject.toJSONString(object));
            jsonData1 = objects.getString(0);
            jsonData2 = objects.getString(1);

            System.out.println("jar包程序读取包内resources下的文件:");
            System.out.println(jsonData1);
            System.out.println(jsonData2);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}

相关文章

Web应用启动自动运行代码的三种方案

相关推荐
邪修king5 小时前
Re:Linux 系统篇(三十五):进程间通信Chapter2:从匿名管道到进程池:Linux 进程间通信实战(深度理解「先描述,再组织」)
java·linux·运维
拆房老料6 小时前
【第四部分:Agentic 智能体设计模式】16. 一个 Prompt 搞不定复杂任务?试试 Prompt Chaining
java·前端·人工智能·设计模式·prompt
张张123y6 小时前
后端第十四课:Agent 记忆系统(让 Agent 记住上下文和用户,跨会话不健忘)
java·大数据·人工智能·python·agent·记忆
曹牧11 小时前
C#:空合并运算符
java·前端·数据库
布吉岛的石头11 小时前
Java 程序员第 50 阶段2:预训练的目标函数:自回归语言建模本质
java·开发语言·人工智能·深度学习·回归·transformer
golang学习记12 小时前
IDEA 2026年的玩法已经完全不同
java·ide·intellij-idea
紧跟先前的步伐12 小时前
Go AI Agent 实战 05|Temperature 与生成参数:让模型输出可控
java·人工智能·golang
金銀銅鐵12 小时前
[Java] 展示添加元素时 ArrayList 的内部变化
java·后端·ai编程
斌糖雪梨12 小时前
spring auth 核心流程详解
java·后端·spring
文丑颜不良啊14 小时前
LeetCode201~225题目解析
java·leetcode