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)
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值