【问题标题】:Base64 decode to file groovyBase64 解码到文件 groovy
【发布时间】:2015-05-07 05:34:22
【问题描述】:

尝试解码 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()

这会创建一个字节[] 值,例如 [-121,25,-180....] 打印到文件中。 如何获取原始数据到文件中。

【问题讨论】:

  • 你好,能分享一下groovy中文件的编码和解码代码吗?

标签: groovy base64 decode


【解决方案1】:

您可以使用二进制流代替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()
}

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

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

【讨论】:

    【解决方案2】:

    来自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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2013-03-01
      • 2011-05-10
      • 2018-02-22
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      相关资源
      最近更新 更多