为了账号安全,请及时绑定邮箱和手机立即绑定

大文件的 GOLANG Base64 编码和解码大小不匹配

大文件的 GOLANG Base64 编码和解码大小不匹配

Go
慕桂英3389331 2022-10-17 16:51:24
当我尝试使用 golang 对大文件进行 base64 编码和解码时,我发现原始文件和解码文件之间的字节长度不匹配。在我的测试文本文件不匹配(1 字节)新行和二进制文件不匹配(2 字节)期间。什么可能导致这些字节丢失?package mainimport (    "encoding/base64"    "io"    "os"    "log")func Encode(infile, outfile string) error {    input, err := os.Open(infile)    if err != nil {        return err    }    // Close input file    defer input.Close()    // Open output file    output, err := os.Create(outfile)    if err != nil {        return err    }    // Close output file    defer output.Close()    encoder := base64.NewEncoder(base64.StdEncoding, output)    l, err := io.Copy(encoder, input)    if err!=nil {        log.Printf("Failed to encode file:%v",err)        return err    } else {        log.Printf("Wrote %v bytes",l)    }    return nil}func Decode(infile, outfile string) error {    input, err := os.Open(infile)    if err != nil {        return err    }    // Close input file    defer input.Close()    // Open output file    output, err := os.Create(outfile)    if err != nil {        return err    }    // Close output file    defer output.Close()    decoder := base64.NewDecoder(base64.StdEncoding, input)    l, err := io.Copy(output, decoder)    if err!=nil {        log.Printf("Failed to encode file:%v",err)        return err    } else {        log.Printf("Wrote %v bytes",l)    }    return nil}
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

你没有Close()encoder所以它不会刷新所有数据。来自文档(强调我的):

func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser

NewEncoder 返回一个新的 base64 流编码器。写入返回的 writer 的数据将使用 enc 进行编码,然后写入 w。Base64 编码以 4 字节块运行;完成写入后,调用者必须关闭返回的编码器以刷新任何部分写入的块。

我还引用了文档中的示例,其中有一个很好的评论:

package main


import (

    "encoding/base64"

    "os"

)


func main() {

    input := []byte("foo\x00bar")

    encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout)

    encoder.Write(input)

    // Must close the encoder when finished to flush any partial blocks.

    // If you comment out the following line, the last partial block "r"

    // won't be encoded.

    encoder.Close()

}


查看完整回答
反对 回复 2022-10-17
  • 1 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号