Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base64 decode to file groovy

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.

like image 659
Nomad Avatar asked Mar 05 '15 18:03

Nomad


2 Answers

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())
like image 135
Ian Roberts Avatar answered Nov 09 '22 08:11

Ian Roberts


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)
like image 34
Vadzim Avatar answered Nov 09 '22 08:11

Vadzim