ErEcTuS
ErEcTuS

Reputation: 867

Parse a properties file with groovy

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

Upvotes: 0

Views: 5624

Answers (4)

Gasol
Gasol

Reputation: 2519

Interesting problem and answers. All answers seems to be correct to me, but no one answers the root cause.

ConfigSlurper is a simple class, which only has few methods. The most important method are named parse. There is only one parse method that is applicable to properties. the others are for Groovy script file.

javadoc

So based on the document, you are trying to read configuration from a Groovy script, not properties file. That's the reason why it complain as following message. Because Groovy script may declare shebang likes #!/usr/bin/env groovy at the beginning of file.

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

1 error

Here is the modification based on your code to fix the problem

    Properties props = new Properties()
    new File('testdata.properties').withInputStream { props.load(it) }
    def config = new ConfigSlurper().parse(props)
    println config.username

Upvotes: 1

Josh Gagnon
Josh Gagnon

Reputation: 5351

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)

Upvotes: 2

tim_yates
tim_yates

Reputation: 171074

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) 
}

Upvotes: 7

McDowell
McDowell

Reputation: 108859

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)

Upvotes: 1

Related Questions