Go-IO与文件操作从基础读写到高性能大文件处理
文章导语
Go的io包设计精妙——Reader和Writer两个接口统一了所有I/O操作。本文从基础的文件读写到高性能大文件处理,彻底掌握Go的I/O体系。
一、io.Reader/Writer体系
typeReaderinterface{Read(p[]byte)(nint,errerror)}typeWriterinterface{Write(p[]byte)(nint,errerror)}// 一切皆Reader/Writer:文件、网络连接、bytes.Buffer、strings.Reader二、大文件处理技巧
// 逐行读取大文件funcProcessLargeFile(pathstring)error{f,_:=os.Open(path)deferf.Close()scanner:=bufio.NewScanner(f)scanner.Buffer(make([]byte,1024*1024),10*1024*1024)// 10MB行缓冲forscanner.Scan(){process(scanner.Text())}returnscanner.Err()}// io.TeeReader同时读取和写入tee:=io.TeeReader(file,&buf)// io.Pipe管道连接pr,pw:=io.Pipe()gofunc(){pw.Write(data);pw.Close()}()io.ReadAll(pr)三、ioutil到os的迁移
Go 1.16起:ioutil.ReadFile → os.ReadFile,ioutil.ReadAll → io.ReadAll,ioutil.WriteFile → os.WriteFile。
四、全文总结
io.Reader/Writer是一切I/O的抽象基础,bufio提供缓冲I/O,os/filepath处理文件路径,io.Pipe实现goroutine间管道通信。
参考文献
- Go io包文档
- Go Blog - io.Reader in depth
- Go 1.16 Release Notes