2016-02-11 42 views
1

人都不能访问属性文件这样的:是否有Groovier方法来访问属性文件?

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' 

回答

2

我相信答案是否定的。

Groovy JDK enhancements的文档不包含java.util.Properties(与java.io.File相比)。 This article意味着本土解决方案的现有技术。

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' 
1

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

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