包IO提供I/O原語的基本接口衔蹲。它的主要任務(wù)是包裝這些原語的現(xiàn)有實(shí)現(xiàn)
1.Reader讀取器
Reader是一個(gè)包裹基本讀方法的接口,Read讀取len(p)個(gè)bytes到p中勾扭,返回值n代表讀取到的bytes數(shù)囱怕,值范圍為大于等于0小于等于len(p).err為讀取過程遇到的錯(cuò)誤紧武。即使read返回n<len(p),它也可以在調(diào)用期間使用p的所有部分作為臨時(shí)空間按厘。read通常返回可用的內(nèi)容抵恋,而不是等待更多內(nèi)容。
該接口只有Read一個(gè)方法挠日,任何實(shí)現(xiàn)了該方法的類型都可以說是實(shí)現(xiàn)了讀取器的功能疮绷。在參數(shù)類型為Reader時(shí),都可以當(dāng)做Reader類型傳入嚣潜。
Read方法參數(shù)為一個(gè)字節(jié)切片冬骚,數(shù)據(jù)讀取,寫入到該切片中懂算,返回值類型為一個(gè)int類型只冻,標(biāo)識(shí)讀取到的字節(jié)數(shù),err標(biāo)識(shí)讀取過程中遇到的任何異常计技,當(dāng)讀取結(jié)束后喜德,err返回值為io.EOF
.該值標(biāo)識(shí)讀取內(nèi)容結(jié)束,不能作為一般的異常處理垮媒。
type Reader interface {
Read(p []byte) (n int, err error)
}
2.Writer
Writer是包裹了基本寫方法的接口舍悯。
Write從p中寫len(p)個(gè)字節(jié)到底層的數(shù)據(jù)流航棱,返回值n代表成功寫入的bytes數(shù),值范圍為0<=n<=len(p)
,err代表寫時(shí)遇到的錯(cuò)誤萌衬。Write必須返回一個(gè)非空的錯(cuò)誤丧诺,如果n<len(p),Write不能修改參數(shù)切片
type Writer interface {
Write(p []byte) (n int, err error)
}
types.Buffer類型實(shí)現(xiàn)了Write方法。
// Write appends the contents of p to the buffer, growing the buffer as
// needed. The return value n is the length of p; err is always nil. If the
// buffer becomes too large, Write will panic with ErrTooLarge.
func (b *Buffer) Write(p []byte) (n int, err error) {
b.lastRead = opInvalid
m, ok := b.tryGrowByReslice(len(p))
if !ok {
m = b.grow(len(p))
}
return copy(b.buf[m:], p), nil
}
package main
import (
"bytes"
"fmt"
"os"
)
func main() {
mircors := []string{
"Micro為構(gòu)建微服務(wù)提供了一些基本模板奄薇,",
"目標(biāo)就是要讓開發(fā)分布式系統(tǒng)盡可能地簡化驳阎。",
"因?yàn)槲⒎?wù)自身就是一個(gè)結(jié)構(gòu),",
"所以micro希望通過工具在邏輯層面上進(jìn)行職責(zé)分離馁蒂。",
}
var writer bytes.Buffer
for _, m := range mircors {
n, err := writer.Write([]byte(m))
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if n != len(m) {
fmt.Println("write data error")
os.Exit(1)
}
}
fmt.Println(writer.String())
}
3.ReadWriter
// ReadWriter is the interface that groups the basic Read and Write methods.
type ReadWriter interface {
Reader
Writer
}
4.ReaderFrom
ReadFrom從r讀取數(shù)據(jù)直到遇到EOF或者error.
type ReaderFrom interface {
ReadFrom(r Reader) (n int64, err error)
}
5.WriterTo
WriteTo向w中寫數(shù)據(jù)呵晚,直到?jīng)]有更多的數(shù)據(jù)可寫或者遇到錯(cuò)誤。
type WriterTo interface {
WriteTo(w Writer) (n int64, err error)
}
6.ReaderAt
ReadAt讀取len(p)個(gè)字節(jié)到p從輸入源的off偏移量開始沫屡。返回讀取到的字節(jié)數(shù)和遇到的任何錯(cuò)誤饵隙。如果ReadAt返回的n<len(p),同時(shí)將返回一個(gè)非空的錯(cuò)誤,解釋了為什么返回的字節(jié)數(shù)少沮脖,在這種層面上金矛,ReadAt要嚴(yán)于Read.如果n=len(p), err == EOF或者err==nil.
type ReaderAt interface {
ReadAt(p []byte, off int64) (n int, err error)
}
7.WriterAt
WriterAt將len(p)個(gè)字節(jié)從p中寫入到數(shù)據(jù)流中,寫入時(shí)從偏移量off開始勺届。返回寫入的字節(jié)數(shù)和任何遇到錯(cuò)誤驶俊。如果n<len(p),返回的err非空。
type WriterAt interface {
WriteAt(p []byte, off int64) (n int, err error)
}
8.Copy
從src中復(fù)制數(shù)據(jù)到dst直到在src中遇到EOF,或者產(chǎn)生錯(cuò)誤免姿。返回復(fù)制的bytes數(shù)量饼酿,和復(fù)制中遇到的錯(cuò)誤。
一個(gè)成功的復(fù)制胚膊,返回的err==nil,而不是err==EOF.因?yàn)镃opy被定義為從src中讀取直到EOF.它并不會(huì)把EOF當(dāng)做一個(gè)錯(cuò)誤來對(duì)待故俐。如果src實(shí)現(xiàn)了WriterTo接口,copy通過調(diào)用src.WriteTo(dst)來實(shí)現(xiàn)紊婉。否則药版,如果dst實(shí)現(xiàn)了ReaderFrom接口,copy通過調(diào)用dst.ReadFrom(src)來實(shí)現(xiàn)喻犁。
func Copy(dst Writer, src Reader) (written int64, err error) {
return copyBuffer(dst, src, nil)
}
示例:
package main
import (
"fmt"
"io/ioutil"
"strings"
"os"
"io"
)
func main(){
content, err := ioutil.ReadFile("./demo.go")
if err != nil {
fmt.Println(err)
}
fmt.Printf("file content: %s", content)
r := strings.NewReader("Hello World!")
n, err := io.Copy(os.Stdout, r)
fmt.Printf("\n%d, %v", n, err) //12, <nil>
}
9.StringWriter
將字符串內(nèi)容寫到w中槽片,接受一個(gè)字節(jié)切片,如果w實(shí)現(xiàn)了StringWriter接口株汉,則直接調(diào)用筐乳,調(diào)用w.Write方法。
type StringWriter interface {
WriteString(s string) (n int, err error)
}
func WriteString(w Writer, s string) (n int, err error) {
if sw, ok := w.(StringWriter); ok {
return sw.WriteString(s)
}
return w.Write([]byte(s))
}
示例:
nstr, errstr := io.WriteString(os.Stdout, "Hello world")
fmt.Printf("\n%d, %v", nstr, errstr)