-
Notifications
You must be signed in to change notification settings - Fork 1
/
demo5_copy.go
executable file
·80 lines (68 loc) · 1.41 KB
/
demo5_copy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"fmt"
"io"
"io/ioutil"
"os"
)
func main() {
srcFile := "E:/GoPath/src/a/1.png"
desFile := "E:/GoPath/src/a/222.png"
//total,err := CopyFile1(srcFile, desFile)
//total,err := CopyFile2(srcFile, desFile)
total,err := CopyFile3(srcFile, desFile)
fmt.Println(total, err)
}
func CopyFile3(srcFile, destFile string)(int, error) {
bs,err := ioutil.ReadFile(srcFile)
if err != nil {
return 0,err
}
err = ioutil.WriteFile(destFile,bs,0777)
if err != nil {
return 0,err
}
return len(bs), nil
}
func CopyFile2(srcFile, destFile string)(int64, error) {
file1,err := os.Open(srcFile)
if err != nil {
return 0, err
}
file2,err := os.OpenFile(destFile,os.O_WRONLY|os.O_CREATE,os.ModePerm)
if err != nil {
return 0, err
}
defer file1.Close()
defer file2.Close()
return io.Copy(file2, file1)
}
func CopyFile1(srcFile, destFile string)(int, error) {
file1,err := os.Open(srcFile)
if err != nil {
return 0, err
}
file2,err := os.OpenFile(destFile,os.O_WRONLY|os.O_CREATE,os.ModePerm)
if err != nil {
return 0, err
}
defer file1.Close()
defer file2.Close()
//读写
bs := make([]byte, 1024, 1024)
n := -1 //读取的数据量
total := 0
for{
n,err = file1.Read(bs)
if err == io.EOF || n == 0 {
fmt.Println("拷贝完毕")
break
} else if err != nil {
fmt.Println("报错了:", err)
return total, err
}
total += n
file2.Write(bs[:n])
}
return total,nil
}