Honza Sestak
Honza Sestak

Reputation: 115

How to write properties file in Groovy without escape characters and single quotes?

I have something like:

def newProps = new Properties()
def fileWriter = new OutputStreamWriter(new FileOutputStream(propsFile,true), 'UTF-8')
def lineSeparator = System.getProperty("line.separator")

newProps.setProperty('SFTP_USER_HASH', userSftpHome.toString())
newProps.setProperty('GD_SFTP_URI', sftpHost.toString())

fileWriter.write(lineSeparator)
newProps.store(fileWriter, null)
fileWriter.close()

The problem is that store() method escapes ":" or "=" characters with backslash (). I don't want that because I store there some passwords and tokens and need to copy those values strictly in the key=value format.

Also, when I use the configSlurper, it stores the values with single quotes, like:

key='value'

Is there any solution for that? Saving in unescaped key=value format to properties file in Groovy?

Upvotes: 3

Views: 7974

Answers (2)

tim_yates
tim_yates

Reputation: 171084

You could do this:

def newProps = new Properties()
newProps.setProperty('SFTP_USER_HASH', 'woo')
newProps.setProperty('GD_SFTP_URI', 'ftp://woo.com')

propsFile.withWriterAppend( 'UTF-8' ) { fileWriter ->
    fileWriter.writeLine ''
    newProps.each { key, value ->
        fileWriter.writeLine "$key=$value"
    }
}

BUT, so long as you are reading the properties in with load, there should be no need for this as it should de-escape any escaped characters

Upvotes: 6

Durandal
Durandal

Reputation: 5663

The JDK's built in Properties class does that escaping by design. According to the Docs:

Then every entry in this Properties table is written out, one per line. For each entry the key string is written, then an ASCII =, then the associated element string. For the key, all space characters are written with a preceding \ character. For the element, leading space characters, but not embedded or trailing space characters, are written with a preceding \ character. The key and element characters #, !, =, and : are written with a preceding backslash to ensure that they are properly loaded.

You can however, override this behavior by sub-classing the Properties class yourself. You'd need to override the load and store methods yourself and read/write yourself. It would be pretty straight forward; pretty good examples found here: Link

Upvotes: 1

Related Questions