我的文件格式如下:
name = David
city = tokyo
Asia.COuntry.origin = Japan
name = mia
city = kuala lampur
SouthAsia.COuntry.origin = malaysia
name = bilal
city = karachi
NorthAsia.COuntry.origin = pakistan
name = Murphy
city = london
europe.COuntry.origin = england
我在下面编写了代码来制作上述文件的地图:
def File = new File("C:/Users/.................")
def Prop = new Properties()
File.withInputStream { stream ->
Prop.load(stream)
}
现在使用变量作为Key,我可以从上面的地图中获取值,如下所示:
{ "$Prop.'Asia.COuntry.origin'}"
问题:上述文件中的值不是静态的,上述文件中可能包含任何人,因此我无法通过" KEY"获取cOuntry.origin的值。 有没有办法搜索那些有" country.origin"附加在尾部并搜索包含" country.origin"的所有密钥。并且正如我上面所做的那样逐一传递密钥。
答案 0 :(得分:1)
您可以轻松搜索密钥以COuntry.origin
结尾的所有条目并对其进行处理,但我认为您的方法无论如何都不正确。在Properties
文件中,您只能将每个密钥放一次。
或者你可以多次使用它,但只考虑带有键的最后一行并覆盖前一行。因此,在最终结果中,name
只有一个条目,city
只有一个条目。
我认为您应该将文件读取更改为不使用Properties
,而是执行自定义解析,如new File(...).readLines()
,然后将这些行转换为您需要的数据结构。
答案 1 :(得分:1)
虽然效率不高,但一个选项是编写一个DynamicProps
类,每次加载属性:
class DynamicProps {
def props
def file = new File('data.properties')
def getKeys(def suffix) {
def results = []
props = new Properties()
file.withInputStream { stream ->
props.load(stream)
}
def allKeys = props.propertyNames()
while (allKeys.hasMoreElements()) {
def key = allKeys.nextElement()
if (key ==~ ".*${suffix}") {
results << key
}
}
results
}
}
// -- main
def dynamicProps = new DynamicProps()
println dynamicProps.getKeys(".COuntry.origin")