bufio緩存讀寫

本篇演示通過緩存讀寫

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func ReadBuffer()  {
	strReader := strings.NewReader("hello world")
	bufferReader := bufio.NewReader(strReader)

	/*Peek只讀不取,所以緩存中依然是11個字節*/
	data, _ := bufferReader.Peek(10)
	fmt.Println(string(data))			//輸出:hello worl
	nBytes := bufferReader.Buffered()	//緩存中緩存了多少個字節數
	fmt.Println(nBytes)					//輸出:11

	/*ReadString從緩存中讀,並取出來,所以緩存中還剩5個字節*/
	str, _ := bufferReader.ReadString(' ') //從緩存中讀取數據,讀到第一個空白字符處
	fmt.Println(str)						//hello
	fmt.Println(bufferReader.Buffered())	//5

	/*Read指定從緩存中讀取固定字節*/
	pByte := make([]byte, 10)
	nBytes, err := bufferReader.Read(pByte)
	fmt.Println(nBytes)		//輸出:5
	fmt.Println(err)		//輸出: nil

	/*如果緩存中已無數據,從緩存中讀取,返回0個字節, 錯誤類型爲EOF*/
	pByte1 := make([]byte, 10)
	nBytes1, err1 := bufferReader.Read(pByte1)
	fmt.Println(nBytes1)
	fmt.Println(err1)
}

func WriteBuffer()  {
	writerBuffer := bufio.NewWriter(os.Stdout)
	fmt.Fprint(writerBuffer, "hello ")
	fmt.Fprint(writerBuffer, "world")
	writerBuffer.Flush()	//刷新後,才能從writerBuffer緩存中寫入到文件中
}

func main()  {
	ReadBuffer()
	WriteBuffer()
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章