當我嘗試使用 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
}
uj5u.com熱心網友回復:
你不這樣做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()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/373106.html
上一篇:OPARego問題計數
下一篇:如何制作切片結構的物件?
