在Golang中复制文件的简单方法

前端之家收集整理的这篇文章主要介绍了在Golang中复制文件的简单方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有没有任何简单/快速的方式来复制文件在Go?

我找不到一个快速的方式在文档和搜索互联网没有帮助,以及。

稳健和高效的副本在概念上是简单的,但是由于需要处理由目标操作系统及其配置施加的许多边缘情况和系统限制而不容易实现。

如果你只想复制现有的文件,可以使用os.Link(srcName,dstName)。这避免了在应用程序中移动字节并节省磁盘空间。对于大文件,这是一个重要的时间和空间节省。

但是各种操作系统对于如何使用硬链接有不同的限制。根据您的应用程序和目标系统配置,Link()调用可能无法在所有情况下工作。

如果你想要一个单一的通用,健壮和高效的复制功能,更新Copy()到:

>执行检查以确保至少某种形式的副本将成功(访问权限,目录存在等)
>检查两个文件是否已存在并且是否相同
os.SameFile,如果他们是相同的,返回成功
>尝试链接,如果成功则返回
>复制字节(所有有效的意思都失败),返回结果

优化将是在go程序中复制字节,因此调用者不会在字节副本上阻塞。这样做对调用者施加额外的复杂性以正确处理成功/错误情况。

如果我想要两个,我会有两个不同的副本函数:CopyFile(src,dst string)(错误)的阻塞副本和CopyFileAsync(src,dst字符串)(chan c,错误)通过一个信令通道回呼叫为异步情况。

  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "io"
  6. "os"
  7. )
  8.  
  9. // CopyFile copies a file from src to dst. If src and dst files exist,and are
  10. // the same,then return success. Otherise,attempt to create a hard link
  11. // between the two files. If that fail,copy the file contents from src to dst.
  12. func CopyFile(src,dst string) (err error) {
  13. sfi,err := os.Stat(src)
  14. if err != nil {
  15. return
  16. }
  17. if !sfi.Mode().IsRegular() {
  18. // cannot copy non-regular files (e.g.,directories,// symlinks,devices,etc.)
  19. return fmt.Errorf("CopyFile: non-regular source file %s (%q)",sfi.Name(),sfi.Mode().String())
  20. }
  21. dfi,err := os.Stat(dst)
  22. if err != nil {
  23. if !os.IsNotExist(err) {
  24. return
  25. }
  26. } else {
  27. if !(dfi.Mode().IsRegular()) {
  28. return fmt.Errorf("CopyFile: non-regular destination file %s (%q)",dfi.Name(),dfi.Mode().String())
  29. }
  30. if os.SameFile(sfi,dfi) {
  31. return
  32. }
  33. }
  34. if err = os.Link(src,dst); err == nil {
  35. return
  36. }
  37. err = copyFileContents(src,dst)
  38. return
  39. }
  40.  
  41. // copyFileContents copies the contents of the file named src to the file named
  42. // by dst. The file will be created if it does not already exist. If the
  43. // destination file exists,all it's contents will be replaced by the contents
  44. // of the source file.
  45. func copyFileContents(src,dst string) (err error) {
  46. in,err := os.Open(src)
  47. if err != nil {
  48. return
  49. }
  50. defer in.Close()
  51. out,err := os.Create(dst)
  52. if err != nil {
  53. return
  54. }
  55. defer func() {
  56. cerr := out.Close()
  57. if err == nil {
  58. err = cerr
  59. }
  60. }()
  61. if _,err = io.Copy(out,in); err != nil {
  62. return
  63. }
  64. err = out.Sync()
  65. return
  66. }
  67.  
  68. func main() {
  69. fmt.Printf("Copying %s to %s\n",os.Args[1],os.Args[2])
  70. err := CopyFile(os.Args[1],os.Args[2])
  71. if err != nil {
  72. fmt.Printf("CopyFile Failed %q\n",err)
  73. } else {
  74. fmt.Printf("CopyFile succeeded\n")
  75. }
  76. }

猜你在找的Go相关文章