Eclipse运行正常但Jar包命令行调用报错:资源文件读取异常
解决Jar包中读取resources目录下配置文件的问题
这个问题的核心原因很明确:当你的应用被打包成Jar文件后,resources目录下的配置文件不再是文件系统中的独立文件,而是Jar包内部的一个资源条目。你用objClassLoader.getResource(propFile).getFile()拿到的路径是Jar内部的特殊格式路径(比如file:xxx.jar!/ssh.properties),这种路径无法被FileInputStream识别,自然会抛出FileNotFoundException。
正确的解决方案:使用getResourceAsStream()直接读取资源流
你不需要先获取文件路径再创建文件输入流,直接通过类加载器的getResourceAsStream()方法获取资源的输入流即可,这个方法能直接读取Jar内部的资源。
修改你的getPropertiyByKey方法如下:
public String getPropertiyByKey(String key, String propFile) throws IOException { Properties prop = new Properties(); InputStream objInputStream = null; ClassLoader objClassLoader = getClass().getClassLoader(); String result = ""; try { System.out.println(propFile); // 直接通过getResourceAsStream获取输入流 objInputStream = objClassLoader.getResourceAsStream(propFile); if (objInputStream == null) { throw new FileNotFoundException("资源文件 " + propFile + " 未找到"); } prop.load(objInputStream); result = prop.getProperty(key); } catch (Exception e) { e.printStackTrace(); throw e; // 建议重新抛出异常,方便上层代码处理错误 } finally { if (objInputStream != null) { objInputStream.close(); } } return result; }
额外注意事项
- 确保你的配置文件(
ssh.properties等)确实放在src/main/resources目录下(Maven项目结构),这样打包时Maven会自动把它们包含到Jar包的根目录中。 - 如果是普通Java项目,要在Eclipse中设置资源目录属性:右键项目 -> Build Path -> Configure Build Path -> 选中resources目录,设置为Source Folder,这样打包时才会把资源文件加入Jar。
- 保持使用相对文件名(比如
ssh.properties)即可,类加载器会自动从类路径(包括Jar内部)查找资源,不要硬编码绝对路径。
这样修改后,不管是在Eclipse中运行还是通过Jar包运行,都能正确读取到配置文件了。
内容的提问来源于stack exchange,提问作者Michael Mucci
相关产品推荐
相关产品推荐

