是否有Groovier方法来访问属性文件?

时间:2016-02-11 13:48:36

标签: gradle groovy

可以访问属性文件:

def props = new Properties()
new File('my.props').withInputStream { props.load(it) }
assert props.foo == 'bar'

我觉得这很麻烦。是不是有一种更加时髦的方式?

// does not compile
def props = Properties.from(new File('my.props'))
assert props.foo == 'bar'

3 个答案:

答案 0 :(得分:2)

我相信答案是否定的。

Groovy JDK enhancements的文档不包含java.util.Properties(比较,java.io.File)。 This article暗示了本土解决方案的现有技术。

答案 1 :(得分:1)

您始终可以使用元编程:

Properties.metaClass.static.from = { File f ->
    def p = new Properties()
    f.withInputStream { p.load(it) }
    p
}
p = Properties.from(new File('a.properties'))
assert p['a'] == '10'

答案 2 :(得分:1)

我不知道从文件创建属性的任何快捷方式。我想建议一个没有事先变量声明的简单解决方案:

p = new File('my.props').withReader { reader -> 
    new Properties().with { 
        load reader
        it
    }
}