亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

大文件的 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條經驗 獲得超5個贊

你沒有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 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號