由于getResource方法在jar和idea中获取的路径不同,按照获取协议区分jar和非jar情况
resources/application.properties
custom-key=customValue
ReadPropertiesUtil.java
import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.nio.file.Files; import java.util.Properties; public class ReadPropertiesUtil { public static void main(String[] args) throws IOException { Properties properties = getProperties("application.properties"); properties.forEach((key, value) -> { System.out.println(key + ":" + value); }); } /** * 获取properties文件 * * @param fileName 文件名 * @return pro */ public static Properties getProperties(String fileName) { Properties properties = new Properties(); InputStream inputStream; try { inputStream = getInputStream(fileName); properties.load(inputStream); return properties; } catch (IOException e) { System.out.println("read properties error"); } return properties; } /** * 获取resource资源流 * * @return 路径 */ private static InputStream getInputStream(String fileName) throws IOException { ClassLoader loader = ReadPropertiesUtil.class.getClassLoader(); // 处理class在根路径下的情况,保证一定存在一个路径 String className = ReadPropertiesUtil.class.getName().replace('.', '/') + ".class"; URL url = loader.getResource(className); // URL url = ReadPropertiesUtil.class.getResource(""); // class没有包路径时,jar方式获取不到resource if (url == null) { throw new RuntimeException("unknown resource path"); } String protocol = url.getProtocol(); System.out.println("protocol:" + protocol); if ("file".equals(protocol)) { return Files.newInputStream(new File(loader.getResource(fileName).getPath()).toPath()); } else { return loader.getResourceAsStream(fileName); } } }
备注:
idea获取路径:
file:/X:/fake/target/classes/ReadPropertiesUtil.class
jar执行获取路径:
jar:file:/X:/fake/target/test.jar!/ReadPropertiesUtil.class
执行效果如下:
idea:
jar包:
java -cp test.jar ReadPropertiesUtil
le.li
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)