Base64 decode to file groovy

16,269

Solution 1

You could use a binary stream instead of a Writer:

File f = new File("c:\\document1.doc")
FileOutputStream out = null           
byte[] b1 = Base64.decodeBase64(info.getdata());
out = new FileOutputStream(f)
try {
  out.write(b1)
} finally {
  out.close()
}

But far simpler is to use the Groovy JDK extension File.setBytes:

new File("c:\\document1.doc").bytes = Base64.decodeBase64(info.getdata())

Solution 2

From https://gist.github.com/mujahidk/7fdda0c69d11fc3e4a0907ce4ea77537:

def text = "Going to convert this to Base64 encoding!"

def encoded = text.bytes.encodeBase64().toString()
println encoded

byte[] decoded = encoded.decodeBase64()
println new String(decoded)
Share:
16,269

Related videos on Youtube

Nomad
Author by

Nomad

Updated on September 15, 2022

Comments

  • Nomad
    Nomad over 1 year

    Trying to decode base64 and write it to file using groovy

    File f = new File("c:\\document1.doc")
    PrintWriter writer = null           
    byte[] b1 = Base64.decodeBase64(info.getdata());
    writer = new PrintWriter(f)
    writer.print(b1)
    writer.close()
    

    This creates a byte[] values like [-121,25,-180....] printed to file. How to get original data into the file.