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

当我尝试使用 golang 对大文件进行 base64 编码和解码时,我发现原始文件和解码文件之间的字节长度不匹配。


在我的测试文本文件不匹配(1 字节)新行和二进制文件不匹配(2 字节)期间。


什么可能导致这些字节丢失?


package main


import (

    "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

}


慕桂英3389331
浏览 122回答 1
1回答

收到一只叮咚

你没有Close(),encoder所以它不会刷新所有数据。来自文档(强调我的):func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloserNewEncoder 返回一个新的 base64 流编码器。写入返回的 writer 的数据将使用 enc 进行编码,然后写入 w。Base64 编码以 4 字节块运行;完成写入后,调用者必须关闭返回的编码器以刷新任何部分写入的块。我还引用了文档中的示例,其中有一个很好的评论:package mainimport (    "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()}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go