使用io.Copy结合os.Open和os.Create是Go中推荐的文件拷贝方式,代码简洁且性能良好;可通过自定义缓冲区优化性能,并利用文件元信息保留源文件权限,确保数据安全写入磁盘。

在Golang中实现文件拷贝有多种方式,最常见的是使用标准库中的 io.Copy 函数结合 os.Open 和 os.Create。这种方式简单、高效且适用于大多数场景。
这是推荐的实现方式,代码清晰且性能良好。
func copyFile(src, dst string) error {
    sourceFile, err := os.Open(src)
    if err != nil {
        return err
    }
    defer sourceFile.Close()
    destinationFile, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer destinationFile.Close()
    _, err = io.Copy(destinationFile, sourceFile)
    if err != nil {
        return err
    }
    // 显式提交数据到磁盘
    return destinationFile.Sync()
}
说明:
虽然 io.Copy 内部已有默认缓冲,但你可以自定义缓冲区大小以优化特定场景下的性能。
立即学习“go语言免费学习笔记(深入)”;
func copyFileWithBuffer(src, dst string) error {
    source, err := os.Open(src)
    if err != nil {
        return err
    }
    defer source.Close()
    destination, err := os.Create(dst)
    if err != nil {
        return err
    }
    defer destination.Close()
    buf := make([]byte, 4096)
    for {
        n, err := source.Read(buf)
        if err != nil && err != io.EOF {
            return err
        }
        if n == 0 {
            break
        }
        if _, err := destination.Write(buf[:n]); err != nil {
            return err
        }
    }
    return destination.Sync()
}
如果你希望目标文件具有与源文件相同的权限,可以获取源文件的元信息。
func copyFileWithPerm(src, dst string) error {
    sourceFile, err := os.Open(src)
    if err != nil {
        return err
    }
    defer sourceFile.Close()
    fileInfo, err := sourceFile.Stat()
    if err != nil {
        return err
    }
    destinationFile, err := os.OpenFile(dst, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileInfo.Mode())
    if err != nil {
        return err
    }
    defer destinationFile.Close()
    _, err = io.Copy(destinationFile, sourceFile)
    if err != nil {
        return err
    }
    return destinationFile.Sync()
}
基本上就这些。对于绝大多数用途,第一个方法配合 io.Copy 已经足够。如果需要保留权限或处理大文件时控制内存使用,可以选择增强版本。Go 的标准库设计使得文件操作既安全又高效。
以上就是如何在Golang中实现文件拷贝的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号