Groovy如何读取类路径下Jar包中的属性文件
解决Groovy读取Jar包内属性文件的问题
你遇到的问题核心在于:Jar包内的资源并非文件系统中的独立文件,getResource().getPath()返回的是Jar资源的特殊URL格式(带file:前缀和!分隔符),这种路径无法被FileInputStream识别。
直接使用类加载器的getResourceAsStream()方法即可正确读取Jar内的属性文件,不需要处理路径字符串。以下是修正后的代码:
// 初始化Properties对象 Properties appProps = new Properties() // 通过类加载器获取资源输入流,并自动关闭流(Groovy的withStream语法) this.class.getClassLoader().getResourceAsStream("conf/Config.properties").withStream { inputStream -> appProps.load(inputStream) } // 读取属性值 String appVersion = appProps.getProperty("version") println "appVersion = $appVersion"
也可以用更简洁的Groovy写法:
def appProps = new Properties() appProps.load(this.class.getResourceAsStream("/conf/Config.properties")) def appVersion = appProps.getProperty("version") println "appVersion = $appVersion"
关键说明:
getResourceAsStream()会直接返回资源的输入流,不管资源是在文件系统还是Jar包内,都能正确读取。- 如果使用
this.class.getResourceAsStream(),路径开头的/表示从类路径根目录开始查找;如果不带/,则是相对于当前类所在的包路径查找。 - Groovy的
withStream语法会自动关闭输入流,避免资源泄漏。
内容的提问来源于stack exchange,提问作者H. Dog
相关产品推荐
相关产品推荐

