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

SpringBoot打包JAR部署Linux后读取XML报File is not part of FileSystem错误

问题解决:SpringBoot打包JAR后读取resources目录文件失败

你遇到的问题核心是JAR包内的资源无法通过File对象访问。本地运行时,src/main/resources下的文件是直接存放在文件系统中的,所以resource.getFile()能正常获取;但打包成JAR后,这些资源是嵌入在JAR包这个压缩文件内部的,不再是独立的文件系统实体,调用getFile()就会抛出"File is not part of file system"错误。

修改方案:改用输入流读取资源

直接通过ClassPathResource获取输入流读取文件,这种方式兼容文件系统和JAR包内的资源读取场景。修改后的代码如下:

Resource resource = new ClassPathResource("appSettings.xml");
// 用输入流读取资源,自动关闭流(try-with-resources语法)
try (InputStream inputStream = resource.getInputStream()) {
    XmlMapper xmlMapper = new XmlMapper();
    appSettings settings = xmlMapper.readValue(inputStream, appSettings.class);
    Map<String,String> cGMap = new HashMap<>();
    for(add a : settings.getAdd()){
        String val=ConvertToString(a.getValue());
        cGMap.put(a.getKey(),val);
    }
    return cGMap;
} catch (IOException e) {
    // 按需处理异常,比如打印日志或抛出业务异常
    throw new RuntimeException("读取appSettings.xml配置文件失败", e);
}

额外注意事项

  • 确保appSettings.xml确实放在src/main/resources根目录下,SpringBoot的Maven/Gradle打包插件会自动将该目录下的文件打包进JAR,无需额外配置。
  • 避免硬编码文件路径,始终通过ClassPathResource或注入ResourceLoader来获取资源,防止跨环境路径适配问题。
  • 异常处理时建议添加日志输出,方便后续排查部署时的资源读取问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:27:05