方法:三种
package zdpgo_file
import (
"errors"
"io"
"os"
)
func CopyFile(src, des string) error {
if !IsExist(src) {
return errors.New("要复制的文件不存在")
}
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
fi, _ := srcFile.Stat()
perm := fi.Mode()
desFile, err := os.OpenFile(des, os.O_RDWR|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
defer desFile.Close()
_, err = io.Copy(desFile, srcFile)
return err
}
func CopyFileByWriteFile(src, des string) error {
if !IsExist(src) {
return errors.New("要复制的文件不存在")
}
srcFile, err := os.Open(src)
if err != nil {
return err
}
fi, _ := srcFile.Stat()
perm := fi.Mode()
defer srcFile.Close()
input, err := os.ReadFile(src)
if err != nil {
return err
}
err = os.WriteFile(des, input, perm)
if err != nil {
return err
}
return nil
}
func CopyFileByWriteBuffer(src, des string, bufSize int) error {
if bufSize <= 0 {
bufSize = 1 * 1024 * 1024
}
buf := make([]byte, bufSize)
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
fi, _ := srcFile.Stat()
perm := fi.Mode()
desFile, err := os.OpenFile(des, os.O_CREATE|os.O_RDWR|os.O_TRUNC, perm)
if err != nil {
return err
}
defer desFile.Close()
var n int
for {
n, err = srcFile.Read(buf)
if err != nil && err != io.EOF {
return err
}
if n == 0 {
break
}
if _, err = desFile.Write(buf[:n]); err != nil {
return err
}
}
return nil
}
测试
package zdpgo_file
import "testing"
func TestCopyFile(t *testing.T) {
if err := AddDir("test"); err != nil {
t.Fatal(err)
}
data1 := []struct {
Src string
Dst string
}{
{"copy_file.go", "test/test1.go"},
{"copy_file.go", "test/test2.go"},
{"copy_file.go", "test/test3.go"},
}
for _, tt := range data1 {
v := CopyFile(tt.Src, tt.Dst)
if v != nil {
t.Error(v)
}
}
data2 := []struct {
Src string
Dst string
}{
{"copy_file.go", "test/test11.go"},
{"copy_file.go", "test/test22.go"},
{"copy_file.go", "test/test33.go"},
}
for _, tt := range data2 {
v := CopyFileByWriteFile(tt.Src, tt.Dst)
if v != nil {
t.Error(v)
}
}
data3 := []struct {
Src string
Dst string
}{
{"copy_file.go", "test/test111.go"},
{"copy_file.go", "test/test222.go"},
{"copy_file.go", "test/test333.go"},
}
for _, tt := range data3 {
v := CopyFileByWriteBuffer(tt.Src, tt.Dst, 0)
if v != nil {
t.Error(v)
}
}
}
测试结果