我有一個在兩個實際檔案之間復制的簡單代碼。(它們在同一個磁盤上,但不確定這是否相關。)
func copy(inPath, outPath string) {
inFile, err := os.Open(inPath)
if err != nil {
return fmt.Errorf("cannot open input file on path %q: %w", inPath, err)
}
defer inFile.Close()
outFile, err := os.Create(outPath)
if err != nil {
return fmt.Errorf("cannot create output file on path %q: %w", outPath, err)
}
defer outFile()
if _, err := io.Copy(inFile, outFile); err != nil {
return fmt.Errorf("cannot copy file %q to %q: %w", inPath, outPath, err)
}
}
我現在不確定,我是否應該或不應該使用bufio讀者或作家,或者兩者兼而有之,或者都不使用。
也就是說,如果我應該做類似的事情
func copy(inPath, outPath string) {
inFile, err := os.Open(inPath)
if err != nil {
return fmt.Errorf("cannot open input file on path %q: %w", inPath, err)
}
defer inFile.Close()
outFile, err := os.Create(outPath)
if err != nil {
return fmt.Errorf("cannot create output file on path %q: %w", outPath, err)
}
defer outFile()
if _, err := io.Copy(bufio.NewWriter(outFile), bufio.NewReader(inFile)); err != nil {
return fmt.Errorf("cannot copy file %q to %q: %w", inPath, outPath, err)
}
}
bufio 檔案根本沒有告訴我什么時候使用它,什么時候不使用它。
uj5u.com熱心網友回復:
在這種情況下不要使用 bufio。當給定一個*os.File目的地時, io.Copy 通過呼叫復制檔案dest.ReadFrom(src)。如果源也是一個*os.File,ReadFrom 呼叫作業系統在某些系統上進行復制。
在 ReadFrom 和其他優化不可用的情況下,將 bufio 用于 io.Copy 源和目標仍然沒有任何好處。io.Copy 緩沖區大小為 32k,bufio 默認緩沖區大小為 4K。因為 bufio 型別在傳遞更大的緩沖區時會繞過它們自己的緩沖區,所以 bufio 型別除了分配一些額外的記憶體之外不做任何事情。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/447724.html
標籤:走
上一篇:一對多關聯從一張表中獲取資料
下一篇:處理奇偶值
