我有一個簡單的代碼,可以在兩個實際文件之間進行復制。(它們在同一個磁盤上,但不確定是否相關。)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 文檔根本沒有告訴我什么時候使用它,什么時候不使用它。
1 回答

互換的青春
TA貢獻1797條經驗 獲得超6個贊
不要在這種情況下使用 bufio。當給定*os.File
目的地時,io.Copy 通過調用復制文件dest.ReadFrom(src)
。如果源也是*os.File
,則 ReadFrom 調用操作系統在某些系統上執行復制。
在 ReadFrom 和其他優化不可用的情況下,將 bufio 用于 io.Copy 源和目標仍然沒有任何好處。io.Copy 緩沖區大小為 32k,bufio 默認緩沖區大小為 4K。因為 bufio 類型在傳遞一個更大的緩沖區時會繞過它們自己的緩沖區,所以 bufio 類型除了分配一些額外的內存外什么都不做。
- 1 回答
- 0 關注
- 119 瀏覽
添加回答
舉報
0/150
提交
取消