Friday, December 28, 2007

Groovy Encode / Decode

Recently, I needed to encode and decode some information for a project I was working on. I wrote a quick little snippet to show encoding and decoding a string in the same program.

CODE:


def me = "Jim Shingler"
println "Me: ${me}"

// Encode it
def encoded = me.bytes.encodeBase64()
println "encoded: ${encoded}"

// because I need a string for decoding
StringWriter sw = new StringWriter()
encoded.writeTo(sw)

// Decode it
String decoded = new String(sw.toString().decodeBase64())
assert decoded == me
println "decoded: ${decoded}"


OUTPUT:


Me: Jim Shingler
encoded: SmltIFNoaW5nbGVy
decoded: Jim Shingler

7 comments:

Danno said...

Groovy is a beautiful thing.

afsina said...
This comment has been removed by the author.
afsina said...

well. good but nothing special really. any Base64 class would do the same. Actually they usually do better, that do the string conversion too.

Anonymous said...

i without a doubt love all your writing kind, very useful.
don't quit and keep posting in all honesty , because it simply worth to look through it.
looking forward to read much of your web content, enjoy your day!

levitra cialis said...

I was looking for this information, thanks for put in this easy way, I mean in a easy way to understand it jajaja, well until the next time.

theexilesclan said...

No doubt, the chap is totally fair.

sports handicapping services said...

Nice post once again. Thanks for sharing this kind of informative post.