1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 "os" 8 ) 9 10 // 该函数:用于通过io操作实现文件的拷贝,返回值是拷贝的总数量(字节),错误 11 func CopyFile1(srcFile, destFile string) (int, error) { 12 file1, err := os.Open(srcFile) 13 if err != nil { 14 return 0, err 15 } 16 file2, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, os.ModePerm) 17 if err != nil { 18 return 0, err 19 } 20 defer file1.Close() 21 defer file2.Close() 22 23 //读写 24 bs := make([]byte, 1024, 1024) 25 n := -1 //读取的数据量 26 total := 0 27 for { 28 n, err = file1.Read(bs) 29 if err == io.EOF || n == 0 { 30 fmt.Println("拷贝完毕。。") 31 break 32 } else if err != nil { 33 fmt.Println("报错了。。") 34 return total, err 35 } 36 total += n 37 file2.Write(bs[:n]) 38 } 39 return total, nil 40 } 41 42 func CopyFile2(srcFile, destFile string) (int64, error) { 43 file1, err := os.Open(srcFile) 44 if err != nil { 45 return 0, err 46 } 47 file2, err := os.OpenFile(destFile, os.O_WRONLY|os.O_CREATE, os.ModePerm) 48 if err != nil { 49 return 0, err 50 } 51 defer file1.Close() 52 defer file2.Close() 53 return io.Copy(file2, file1) 54 } 55 56 func CopyFile3(srcFile, destFile string) (int, error) { 57 bs, err := ioutil.ReadFile(srcFile) 58 if err != nil { 59 return 0, err 60 } 61 err = ioutil.WriteFile(destFile, bs, 0777) 62 if err != nil { 63 return 0, err 64 } 65 return len(bs), nil 66 } 67 68 func main() { 69 /* 70 拷贝文件: 71 */ 72 73 srcFile := "D:\\Go\\web2\\aa.txt" 74 destFile := "bb.txt" 75 // 覆盖 destFile 内容 size = srcFile 的部分 76 // total, err := CopyFile1(srcFile, destFile) 77 // 覆盖 destFile 内容 size = srcFile 的部分 78 // total, err := CopyFile2(srcFile, destFile) 79 // 完全重写 80 total, err := CopyFile3(srcFile, destFile) 81 fmt.Println(total, err) 82 }