Golang读取文件

Golang读取文件

type Reader interface {
Read(p []byte) (n int, err error)
}
Reader is the interface that wraps the basic Read method.
Read reads up to len§ bytes into p. It returns the number of bytes read (0 <= n <= len§) and any error encountered. Even if Read returns n < len§, it may use all of p as scratch space during the call. If some data is available but not len§ bytes, Read conventionally returns what is available instead of waiting for more.
When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF.
Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.
Implementations of Read are discouraged from returning a zero byte count with a nil error, except when len§ == 0. Callers should treat a return of 0 and nil as indicating that nothing happened; in particular it does not indicate EOF.

buf := make([]byte, 4096)
for {
	n, err2 := resp.Body.Read(buf)
	if n == 0 {
		fmt.Println("读取完成")
		break
	}
	if err2 != nil && err2 != io.EOF {
		err = err2
		return
	}
	// 累加每一次循环读到的 buf 数据,存入result 一次性返回。
	result += string(buf[:n])
}

参考:
https://pkg.go.dev/io#Reader.Read

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值