Parse a properties file with groovy

2019-08-28 18:20发布

I'm trying to extract the username and password from a properties file containing :

#Fri May 31 09:33:22 CEST 2013 
password=user40_31-05-2013 
username=user40_31-05-2013


File propertiesFile = new File('testdata.properties')
def config = new ConfigSlurper().parse(propertiesFile.toURL())
println(config.username)

I'm having this error:

expecting '!', found 'F' @ line 1, column 2. #Fri May 31 09:33:22 CEST 2013 ^

1 error

thanks in advance

3条回答
女痞
2楼-- · 2019-08-28 19:02

You can save having to close the stream yourself with the more idiomatic:

def props = new Properties()
new File("foo.properties").withInputStream { s ->
  props.load(s) 
}
查看更多
Lonely孤独者°
3楼-- · 2019-08-28 19:05

Use the Properties type:

def props = new Properties()
def stream = new FileInputStream("foo.properties")
try {
  props.load(stream)
} finally {
  stream.close()
}
System.out.println(props)
查看更多
贪生不怕死
4楼-- · 2019-08-28 19:09

Maybe I'm being an idiot here, but isn't the larger problem that he's using a shell-style comment character (#) instead of a groovy comment (// or /* ... */)?

His error message is because # at the beginning of a unix script should be followed by ! and then the path to an interpreter. (Something like #!/bin/sed)

查看更多
登录 后发表回答