Base64解码到文件groovy

Dav*_*ave 6 groovy base64 decode

尝试解码base64并使用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()
Run Code Online (Sandbox Code Playgroud)

这会创建一个打印到文件的byte []值,如[-121,25,-180 ....].如何将原始数据导入文件.

Ian*_*rts 6

您可以使用二进制流而不是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()
}
Run Code Online (Sandbox Code Playgroud)

但更简单的是使用Groovy JDK扩展File.setBytes:

new File("c:\\document1.doc").bytes = Base64.decodeBase64(info.getdata())
Run Code Online (Sandbox Code Playgroud)


Vad*_*zim 6

来自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)
Run Code Online (Sandbox Code Playgroud)