You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Gradle构建Shadow Uber Jar无法读取src/main/resources文件报NoSuchFileException

问题根源

你当前使用File类读取Jar包内资源的写法存在本质错误:File只能识别操作系统文件系统中独立存在的文件,而Uber Jar打包后,product.json是Jar包内部的嵌入资源,路径格式为jar:file:/xxx.jar!/product.json的Jar协议专用格式,File类无法解析该格式路径,因此抛出NoSuchFileException。

解决方案

1. 修改资源读取逻辑

废弃File读取方式,改用getResourceAsStream直接读取资源流,示例代码如下:

import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import com.google.gson.Gson;

public Repository<Product> initializeData() {
    ClassLoader classLoader = getClass().getClassLoader();
    // 直接读取classpath下的资源流
    try (InputStream inputStream = classLoader.getResourceAsStream("product.json")) {
        if (inputStream == null) {
            throw new RuntimeException("classpath下未找到product.json文件");
        }
        // 配合Gson直接从流解析数据,无需中转为本地文件
        Gson gson = new Gson();
        Product[] products = gson.fromJson(new InputStreamReader(inputStream, StandardCharsets.UTF_8), Product[].class);
        
        Repository<Product> productRepository = new ProductRepository();
        // 此处补充将products存入productRepository的业务逻辑
        return productRepository;
    } catch (Exception e) {
        throw new RuntimeException("加载product.json资源失败", e);
    }
}

2. 验证资源打包情况

修改代码后如果仍提示找不到资源,可执行以下命令检查Shadow Jar中是否包含目标文件:

jar tf libs/checkout-service-1.0-SNAPSHOT.jar | grep product.json

如果命令无输出,说明资源未被打入Jar包,需在build.gradle中添加资源配置,确保json文件被正确打包:

processResources {
    from 'src/main/resources'
    include '**/*.json'
}

内容的提问来源于stack exchange,提问作者SRJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 04:39:03