Welcome to Wisdom's Blog

胜日寻芳泗水滨,无边光景一时新。等闲识得东风面,万紫千红总是春。

GOLANG文件拷贝

GOLANG文件拷贝

在Golang中,使用系统自带函数io.Copy()

如:

  •     srcFile := "C:/Users/Wisdom/Desktop/Wisdompic.png" (源文件)
  •     dstFile := "C:/Users/Wisdom/Desktop/Ouxiaobaicopy.png" (目标文件)
将srcFile文件打开并读取到系统内存中,并将读取的内容拷贝到dstFile 路径下,完成拷贝操作!
 
package main
import(
	"fmt"
	"os"
	"io"
	"bufio" 
)

func CopyFile (dstFilePath string,srcFilePath string)(written int64, err error){
	srcFile,err := os.Open(srcFilePath)
	if err != nil{
		fmt.Printf("打开源文件错误,错误信息=%v\n",err)
	}
	defer srcFile.Close()
	reader := bufio.NewReader(srcFile)

	dstFile,err := os.OpenFile(dstFilePath,os.O_WRONLY | os.O_CREATE,0777)
	if err != nil{
		fmt.Printf("打开目标文件错误,错误信息=%v\n",err)
		return
	}
	writer := bufio.NewWriter(dstFile)
	defer dstFile.Close()
	return io.Copy(writer,reader)
}
func main (){
	srcFile := "C:/Users/Wisdom/Desktop/Wisdompic.png"
	dstFile := "C:/Users/Wisdom/Desktop/Ouxiaobaicopy.png"
	_, err :=CopyFile(dstFile,srcFile)
	if err == nil {
		fmt.Printf("完成拷贝,Done\n")
	}else{
		fmt.Printf("未完成拷贝,错误=%v\n",err)
	}
}

  

 

posted on 2019-05-14 16:29  欧小白  阅读(2527)  评论(0)    收藏  举报

导航