一、bytes.NewBuffer和bytes.NewReader
func main() {var byteArr []bytebuf := bytes.NewBuffer(byteArr)buf.Write([]byte("今天不错"))fmt.Println(buf.String())
}
package mainimport ("bytes""fmt"
)func main() {data := []byte("路多辛的所思所想")reader := bytes.NewReader(data)// 读取整个字节数组buf := make([]byte, len(data))_, err := reader.Read(buf)if err != nil {fmt.Println("Read failed:", err)}fmt.Println("Bytes read:", buf)// 读取字节切片的一部分part := make([]byte, 3)_, err = reader.Read(part)if err != nil {fmt.Println("Read failed:", err)}fmt.Println("Bytes read:", part)// 查找并读取字节切片中的某个字符offset, err := reader.Seek(6, 0)if err != nil {fmt.Println("Seek failed:", err)}ch, size, err := reader.ReadRune()if err != nil {fmt.Println("ReadRune failed:", err)}fmt.Printf("Read %c with size %d at offset %d\n", ch, size, offset)
}
二、strings.NewReader(没有newWriter)
r := strings.NewReader("abcdefghijklmn")fmt.Println(r.Len()) // 输出14 初始时,未读长度等于字符串长度var buf []bytebuf = make([]byte, 5)readLen, err := r.Read(buf)fmt.Println("读取到的长度:", readLen) //读取到的长度5if err != nil {fmt.Println("错误:", err)}fmt.Println(buf) //adcdefmt.Println(r.Len()) //9 读取到了5个 剩余未读是14-5fmt.Println(r.Size()) //14 字符串的长度
三、bufio.NewReader和bufio.NewWriter
package main
import ("fmt""io""os"
)
func main() {fmt.Println("嗨客网(www.haicoder.net)")fileName := "C:/haicoder.txt"file, err := os.Open(fileName)if err != nil{fmt.Println("Read file err, err =", err)return}defer file.Close()var chunk []bytebuf := make([]byte, 1024)for{n, err := bufio.NewReader(buf)if err != nil && err != io.EOF{fmt.Println("read buf fail", err)return}//说明读取结束if n == 0 {break}//读取到最终的缓冲区中chunk = append(chunk, buf[:n]...)}fmt.Println("File Content =", string(chunk))
}
package main
import ("bufio""fmt""io/ioutil""os"
)
func main() {fmt.Println("嗨客网(www.haicoder.net)")var(fileName = "C:/haicoder.txt"content = "Hello HaiCoder"file *os.Fileerr error)//使用追加模式打开文件file, err = os.OpenFile(fileName, os.O_APPEND, 0666)if err != nil{fmt.Println("Open file err =", err)return}defer file.Close()writer := bufio.NewWriter(file)//写入文件n, err := writer.Write([]byte(content))if err != nil{fmt.Println("Write file err =", err)return}fmt.Println("Write file success, n =", n)writer.Flush()//读取文件fileContent, err := ioutil.ReadFile(fileName)if err != nil{fmt.Println("Read file err =", err)return}fmt.Println("Read file success =", string(fileContent))
}
总结:
1、使用的newbuffer,缓存区是用来存储内容的,并不能确定具体需要的内存大小,因此newbuffer的参数为不固定的[]byte{};
2、使用的newreader,缓存区应该是有数值的,此时是用来读取其中的内容。