Golang学习日志 ━━ 实现io.copy的几种方式

golang自带copy文件功能,但是网上主要是有二种copy的方式,一种是利用系统自带的os.copy方法,一种是利用系统的read和write方法手动造轮实现copy功能,第三种是利用bufio的缓冲方式来实现。

最近的一次代码,利用copy方法,数据却死活写不进新文件。。。直到最后才发现是自己没写defer,提前把写文件给close()了,这种低级错误也是醉了,

实际使用的时候可以多种方式混合。举例如下:

//纯粹以手动读写方式实现copy功能
func copyFilebyRW() {

	fmt.Println("========拷贝文件============")

	c1, err := ioutil.ReadFile("./1.txt")

	if err != nil {
		fmt.Println("读取错误")
	}

	err = ioutil.WriteFile("./2.txt", c1, 6044)
	if err != nil {
		fmt.Println("录入失败")
	}
}

//读取,copy到write中
func copyFileOStoOS() {
	srcFile, err := os.Open("./1.txt")
	defer srcFile.Close()

	if err != nil {
		fmt.Println("srcfile获取失败")
		return
	}

	dstFile, err := os.OpenFile("./2.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	defer dstFile.Close()

	if err != nil {
		fmt.Println("dstfile获取失败")
		return
	}

	rtn, err := io.Copy(dstFile, srcFile)

	if err != nil {
		fmt.Println("copy失败")
	}

	fmt.Println("copy结束:", rtn)
}

//读取缓冲,copy到不缓冲write中
func copyFileBufftoOS() {
	srcFile, err := os.Open("./1.txt")
	defer srcFile.Close()

	if err != nil {
		fmt.Println("srcfile获取失败")
		return
	}

	srcBuf := bufio.NewReader(srcFile)

	dstFile, err := os.OpenFile("./2.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	defer dstFile.Close()

	if err != nil {
		fmt.Println("dstfile获取失败")
		return
	}

	rtn, err := io.Copy(dstFile, srcBuf)

	if err != nil {
		fmt.Println("copy失败")
	}

	fmt.Println("copy结束:", rtn)
}

//读取,copy到缓冲write中
func copyFileOStoBuff() {
	srcFile, err := os.Open("./1.txt")
	defer srcFile.Close()

	if err != nil {
		fmt.Println("srcfile获取失败")
		return
	}

	dstFile, err := os.OpenFile("./2.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	defer dstFile.Close()

	if err != nil {
		fmt.Println("dstfile获取失败")
		return
	}
	dstBuf := bufio.NewWriter(dstFile)

	rtn, err := io.Copy(dstBuf, srcFile)

	if err != nil {
		fmt.Println("copy失败")
	}

	// 进入缓冲后输出,这步骤非常重要,否则虽然read成功了,但write文件为空
	dstBuf.Flush()

	fmt.Println("copy结束:", rtn)
}

//读取缓冲,copy到缓冲write中
func copyFileBufftoBuff() {
	srcFile, err := os.Open("./1.txt")
	defer srcFile.Close()

	if err != nil {
		fmt.Println("srcfile获取失败")
		return
	}

	srcBuf := bufio.NewReader(srcFile)

	dstFile, err := os.OpenFile("./2.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	defer dstFile.Close()

	if err != nil {
		fmt.Println("dstfile获取失败")
		return
	}
	dstBuf := bufio.NewWriter(dstFile)

	rtn, err := io.Copy(dstBuf, srcBuf)

	if err != nil {
		fmt.Println("copy失败")
	}

	// 进入缓冲后输出,这步骤非常重要,否则虽然read成功了,但write文件为空
	dstBuf.Flush()

	fmt.Println("copy结束:", rtn)
}

发布了44 篇原创文章 · 获赞 1 · 访问量 3595

猜你喜欢

转载自blog.csdn.net/snans/article/details/104171297