可执行Jar包无法加载Properties文件问题求助
Maven打包Jar后无法读取resources配置文件的问题解决
问题根源
- 你现在用
System.getProperty("user.dir")拼接路径读取文件,本质是读本地文件系统里的物理文件。但打包成Jar后,src/test/resources下的配置文件会被打包到Jar包内部,变成Jar里的一个资源条目,不再是外部文件系统的独立文件,自然找不到。 - 另外,
src/test/resources是Maven的测试资源目录,默认情况下打包主Jar的时候不会把这个目录下的文件包含进去,只有运行测试代码时才会加载。
解决步骤
1. 调整资源文件位置(可选但推荐)
如果这个配置文件是测试代码专用的,继续放在src/test/resources;如果是主程序运行需要的,移到src/main/resources下,Maven会自动把这个目录的文件打包到Jar的classpath根目录。
2. 修改代码读取方式
用类加载器读取Jar内的资源,替换原来的FileInputStream方式:
try { prop = new Properties(); // 用类加载器获取资源流,路径是相对于classpath的路径 InputStream propFile = YourTestClass.class.getClassLoader().getResourceAsStream("config/my.properties"); // 也可以用当前类直接获取,注意路径开头要加斜杠 // InputStream propFile = YourTestClass.class.getResourceAsStream("/config/my.properties"); if (propFile == null) { System.out.println("资源文件不存在"); return; } prop.load(propFile); } catch (IOException e) { System.out.println("IO异常: " + e.getMessage()); }
- 路径说明:如果文件在
src/test/resources/config/my.properties,那么classpath下的路径就是config/my.properties(类加载器方式不需要开头斜杠;当前类方式需要加斜杠表示根路径)。
3. 确保打包时包含测试资源(如果是测试代码打包)
如果你的可执行Jar是用来运行测试的,需要配置Maven插件把测试资源和测试类一起打包。比如在pom.xml的<build><plugins>中添加以下配置:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.6.0</version> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <archive> <manifest> <!-- 指定TestNG的运行类作为主类 --> <mainClass>org.testng.TestNG</mainClass> </manifest> </archive> <!-- 强制包含测试资源 --> <includeTestResources>true</includeTestResources> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin>
之后运行mvn package就能生成包含依赖和测试资源的可执行Jar。
总结
核心就是不要用文件系统路径读取Jar内部的资源,改用类加载器的资源流方式,同时确保资源文件被正确打包到Jar中。
内容的提问来源于stack exchange,提问作者user3127078
相关产品推荐
相关产品推荐

