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

Spring如何正确访问jar包外部存放的txt文本文件?

Spring Boot加载Jar包外部txt文件解决方案

正确配置方案

  • 方案1(推荐,无需修改启动参数)
    1. 保留Jar包内application.properties中的配置:nameFile=${auth.nameList}
    2. 外部/apps/conf/application-dev.properties修改配置为:
      auth.nameList=file:/apps/conf/nameList.txt
      
    3. 确认代码中使用Spring的Resource接口接收该配置,示例代码:
      @Value("${nameFile}")
      private Resource nameFile;
      
      // 读取文件流示例
      try (InputStream inputStream = nameFile.getInputStream()) {
          // 自定义文件内容处理逻辑
      }
      
  • 方案2(保留classpath前缀写法,需调整启动参数)
    1. 启动命令新增类路径指定,修改为:
      java -cp /apps/conf/:your-app.jar -Dspring.config.location=/apps/conf/application-dev.properties com.xxx.YourMainClass
      
    2. 外部配置修改为:
      auth.nameList=classpath:nameList.txt
      

之前方案失败原因说明

  • 第一种方案失败:classpath:协议只会扫描JVM已配置的类路径目录,/apps/conf默认不在类路径范围内,因此无法定位到文件。
  • 第二种方案失败:未加资源协议前缀的路径,Spring默认会按照classpath:协议处理,仍然到类路径下查找,不会读取文件系统的绝对路径。

额外注意事项

  • 确保运行Jar包的系统用户对/apps/conf/nameList.txt有可读权限,避免权限不足导致的读取失败。
  • 如果代码中之前是将nameFile作为普通字符串路径,自行通过new File(path)读取,需要去掉file:前缀后再创建File对象,或者统一改用Resource接口简化多协议适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 13:51:01