|
在 有哪些简单/快速的方法?Go 复制文件?; v8 ^8 O% p7 J1 a7 g9 N
我在 Doc 找不到快速的方法,在网上搜索也没用。
* C& v N, U6 J
* q% [8 ]5 T+ [ 解决方案: 5 l, d" [8 d) | k
警告:这个答案主要是关于向文件添加硬链接,而不是复制内容。
4 H3 X+ L, ]8 Z2 L% U一个强大的和高效率副本的概念很简单,但不容易实现,因为目标操作系统强加了一些边缘条件和系统限制。
# Y' V1 B) j S% g. G5 D" }如果您只想复制现有文件,您可以使用os.Link(srcName,dstName). 这避免了字节必须在应用程序中移动和磁盘空间。对于大文件,它可以节省大量的时间和空间。
/ C$ U7 @ ~3 g+ ?但是各种操作系统对硬链接的工作方式有不同的限制。根据您的应用程序和目标系统配置,Link()调用可能在所有情况下都不有效。1 _% |9 ^" L" i( j
如果您想要一个通用、健壮且高效的复制功能,请更新Copy()为:
3 c8 G. L/ h9 f. u7 g* x6 j[ol]执行检查以确保至少以某种形式成功复制(访问权限、目录存在等) j$ r- g( {, ~7 n& T
检查两个文件是否存在并使用相同的 os.SameFile,如果它们是一样的,它们就会回到成功 V' Q [4 d! j% Y+ ?
尝试链接,成功返回+ Q$ P. c0 x+ R7 p
复制字节(所有有效手段失败),返回结果[/ol]优化是在 go 例程中复制字节,使调用者不会阻止字节复制。这将给调用者带来额外的复杂性,以正确处理成功/错误。7 h+ a& H2 ]4 n1 s* F* a9 ?& e4 L
如果我想要两者,我将有两个不同的复制功能:CopyFile(src,dst string) (error)用于阻塞复制和复制CopyFileAsync(src,dst string) (chan c,error)将信号通道传输回异步调用器。6 h9 u K3 [0 n6 v
[code]package mainimport "fmt" "io" "os")// CopyFile copies a file from src to dst. If src and dst files exist,and are// the same,then return success. Otherise,attempt to create a hard link// between the two files. If that fail,copy the file contents from src to dst.func CopyFile(src,dst string) (err error) sfi,err := os.Stat(src) if err != nil return } if !sfi.Mode().IsRegular() // cannot copy non-regular files (e.g.,directories, symlinks,devices,etc.) return fmt.Errorf("CopyFile: non-regular source file %s (%q)",sfi.Name(),sfi.Mode().String()dfi,err := os.Stat(dst) if err != nil if !os.IsNotExist(err) return else if !(dfi.Mode().IsRegular()) return fmt.Errorf("CopyFile: non-regular destination file %s (%q)",dfi.Name(),dfi.Mode().String()) if os.SameFile(sfi,dfi) return if err = os.Link(src,dst); err == nil return } err = copyFileContents(src,dst) return}// copyFileContents copies the contents of the file named src to the file named// by dst. The file will be created if it does not already exist. If the// destination file exists,all it's contents will be replaced by the contents// of the source file.func copyFileContents(src,dst string) (err error) in,err := os.Open(src) if err != nil return } defer in.Close() out,err := os.Create(dst) if err != nil return } defer func() cerr := out.Close() if err == nil err = cerr } }() if _,err = io.Copy(out,in); err != nil return } err = out.Sync() return}func main() fmt.Printf("Copying %s to %s\n",os.Args[1],os.Args err := CopyFile(os.Args[1],os.Args if err != nil fmt.Printf("CopyFile failed %q\n",err) else fmt.Printf("CopyFile succeeded\n") code] |
|