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

Java程序在Ubuntu运行找不到配置文件,Windows正常该如何解决?

问题原因

你的猜测完全正确,该报错的核心原因是Ubuntu环境下运行的是编译打包后的jar文件,不存在本地开发时的src目录文件结构:

  • 本地Windows IDE运行时,工作目录为项目根目录,src/main/java/xxx路径真实存在于本地文件系统,因此FileReader可以正常读取文件
  • 打包成jar后,所有编译后的class文件、资源文件均封装在jar包内部,不属于操作系统文件系统的独立文件,无法通过文件路径直接用FileReader读取

修复方案

步骤1:调整资源文件存放规则

按照Maven标准规范,推荐将配置文件放到src/main/resources目录下,例如新建src/main/resources/strategies目录,将agent_0001.config移入该目录。
如果你不想改动原有文件位置,可在pom.xml的build节点添加如下配置,让Maven打包时将java目录下的.config文件一并打入classpath:

<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.config</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
        </resource>
    </resources>
</build>

步骤2:修改文件读取逻辑

放弃使用FileReader,改用类加载器从classpath读取资源流,修改后的代码如下:

// 配置文件放在src/main/resources/strategies下时用该路径
try(InputStream inputStream = getClass().getResourceAsStream("/strategies/agent_0001.config")) {
    // 配置文件保留在原src/main/java/com/honda/strategies下时,路径改为"/com/honda/strategies/agent_0001.config"
    
    if(inputStream == null) {
        throw new RuntimeException("策略配置文件不存在");
    }
    Properties properties = new Properties();
    properties.load(inputStream);

    String template = properties.getProperty("template");
    String market = properties.getProperty("market");
    String coin = properties.getProperty("coin");

    AgentStrategy agentStrategy = new AgentStrategy();
    agentStrategy.setTemplate(template);
    agentStrategy.setMarket(market);
    agentStrategy.setCoin(coin);

    return agentStrategy;
    
} catch (Exception e) {
    e.printStackTrace();
    return null;
}

方案说明

该读取方式会直接从classpath下查找资源,兼容本地IDE运行、jar包运行两种场景,无需硬编码任何环境路径,可跨Windows、Linux等多环境正常运行。

内容的提问来源于stack exchange,提问作者A. Vreeswijk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 11:36:01