Go语言复制文件

需要使用io包的Copy方法

package main

import (
"fmt"
"io"
"os"
)

//自己编写一个函数,接收两个文件路径 srcFileName dstFileName
func CopyFile(dstFileName string,srcFileName string) (written int64,err error) {

srcFile,err := os.Open(srcFileName)

if err != nil {
    fmt.Printf("open file err = %v\n",err)
    return
}

defer srcFile.Close()

//打开dstFileName

dstFile,err := os.OpenFile(dstFileName,os.O_WRONLY | os.O_CREATE,0755)
if err != nil {
    fmt.Printf("open file err = %v\n",err)
    return
}

defer dstFile.Close()

return io.Copy(dstFile,srcFile)

}

func main() {

result,err := CopyFile("./src/main/dst.png","./src/main/file.png")

if err == nil {
    fmt.Println("拷贝成功!,拷贝的字节数为: ",result)
}

}

还可以使用下面的方法

package main

import (
"bufio"
"fmt"
"io"
"os"
)

//自己编写一个函数,接收两个文件路径 srcFileName dstFileName

func CopyFile(dstFileName string,err)
return
}

defer srcFile.Close()

//通过srcFile,获取到Reader
reader := bufio.NewReader(srcFile)

//打开dstFileName
dstFile,0666)
if err != nil {
    fmt.Printf("open file err = %v\n",err)
    return
}

writer := bufio.NewWriter(dstFile)
defer func() {
    writer.Flush() //把缓冲区的内容写入到文件
    dstFile.Close()

}()

return io.Copy(writer,reader)

}

func main() {

result,"./src/main/file.png")

if err == nil {
    fmt.Println("拷贝成功!拷贝的字节大写为: ",result)
}

}

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...