使用案例的不完整代码
file, err := os.Open(“xxx.txt”)
const fileChunk = 1 * (1 << 20) // 1 MB
partSize := int(math.Min(fileChunk, float64(fileSize-int64(i*fileChunk)))) //不足fileChunk大小以实际大小为准
partBuffer := make([]byte, partSize) //新建partSize大小的数组
file.Read(partBuffer) //读取大小为partSize的file至partBuffer数组
左移 (1 << 20) = 1MB
1<< 20 也就是1 * 2^20=1MB。
Go库代码
// Read reads up to len(b) bytes from the File.
// It returns the number of bytes read and any error encountered.
// At end of file, Read returns 0, io.EOF.
func (f *File) Read(b []byte) (n int, err error) {
if err := f.checkValid("read"); err != nil {
return 0, err
}
n, e := f.read(b)
return n, f.wrapErr("read", e)
}
参数
- f 打开的文件句柄。
- b 读取文件内容存放的指针。
返回值
- n 读取到的字节数。
- err 如果读取失败,返回错误信息,否则,返回 nil。
文件读取结束的标志是返回的 n 等于 0,因此,如果我们需要读取整个文件内容,那么我们需要使用 for 循环 不停的读取文件,直到 n 等于 0。
如果没有读取完毕,n 应该记录的是 此时读取到的第几字节。