一. 拷贝文件内容到另一个文件位置
func copyContent() {
filepath1 := "d:/abc.txt"
filepath2 := "e:/eee.txt"
data, err := os.ReadFile(filepath1)
if err != nil {
fmt.Println("read file wrong:", err)
return
}
fmt.Println("读取数据是:", string(data))
err = os.WriteFile(filepath2, data, 0666)
if err != nil {
fmt.Println("write file wrong:", err)
return
}
fmt.Println("操作完成")
}
二. 判断文件是否存在
func PathExists(filepath string) (bool, error) {
fileInfo, err := os.Stat(filepath)
fmt.Println(fileInfo, err)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
三. 拷贝文件(图片、视频)
func CopyFile(distFileName string, srcFileName string) (written int64, err error) {
file, err := os.Open(srcFileName)
if err != nil {
fmt.Println("open source file error:", err)
}
reader := bufio.NewReader(file)
disFile, err := os.OpenFile(distFileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Println("open destination file error:", err)
return
}
writer := bufio.NewWriter(disFile)
written, err = io.Copy(writer, reader)
return
}
四. 测试
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
dis := "e:/666.png"
src := "c:/users/coderyeah/desktop/welt.jpg"
written, err := CopyFile(dis, src)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("copy字节数:", written)
fmt.Println("执行完成")
}