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

Gradle Java项目如何读取src/main/resources资源并导出保留目录结构

解决方案

访问resources下的指定文件

不需要额外了解复杂的classpath概念,直接按资源在src/main/resources下的相对路径读取即可,示例代码如下:

// path开头加/代表从resources根目录开始匹配,例如resources下有config/app.properties,就填"/config/app.properties"
InputStream resourceStream = getClass().getResourceAsStream("/你的资源相对路径");

如果返回null就检查路径大小写、层级是否和resources下的实际结构完全一致,该方法只会读取你指定的单个资源,不会扫描其他无关文件。

导出资源到指定目录并保留原有结构

直接使用以下工具类即可实现需求,你只需要维护自己要导出的资源路径列表,完全可控不会出现多余文件:

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class ResourceExporter {
    /**
     * 导出单个resources资源到目标目录
     * @param resourcePath resources下的资源路径,开头加/,例如 "/config/app.properties"
     * @param targetRootDir 导出的根目录,例如 "C:\\tmp"
     * @throws IOException 读写异常
     */
    public void exportSingleResource(String resourcePath, String targetRootDir) throws IOException {
        // 读取资源流,打包成jar后也可正常读取
        try (InputStream inputStream = getClass().getResourceAsStream(resourcePath)) {
            if (inputStream == null) {
                throw new IllegalArgumentException("资源不存在,请检查路径:" + resourcePath);
            }
            // 拼接目标路径,自动保留原有目录结构
            String relativePath = resourcePath.startsWith("/") ? resourcePath.substring(1) : resourcePath;
            Path targetFullPath = Paths.get(targetRootDir, relativePath);
            // 自动创建不存在的父目录
            Files.createDirectories(targetFullPath.getParent());
            // 写入文件,内容完全和原资源一致
            Files.copy(inputStream, targetFullPath);
        }
    }

    public static void main(String[] args) throws IOException {
        ResourceExporter exporter = new ResourceExporter();
        // 自己维护要导出的资源列表,不需要扫描全classpath,不会出现多余文件
        List<String> needExportResources = Arrays.asList(
            "/config/app.properties",
            "/template/report.docx",
            "/data/config.xml"
        );
        // 批量导出到C:\tmp目录
        for (String resPath : needExportResources) {
            exporter.exportSingleResource(resPath, "C:\\tmp");
        }
    }
}

注意事项

  • 该方法本地开发、打包成jar包运行都通用,不需要修改代码
  • 资源路径严格区分大小写,必须和src/main/resources下的结构完全一致
  • 不要尝试将resources当做本地文件目录读取,打包成jar后资源不存在独立的文件路径,用流读取是唯一通用的实现方式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 17:39:02