Go中各种newreader和newbuffer的使用

一、bytes.NewBuffer和bytes.NewReader

cpp 复制代码
func main() {
	var byteArr []byte
	buf := bytes.NewBuffer(byteArr)
	buf.Write([]byte("今天不错"))
 
	fmt.Println(buf.String())
}
cpp 复制代码
package main
 
import (
	"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)

cpp 复制代码
	r := strings.NewReader("abcdefghijklmn")
	fmt.Println(r.Len())   // 输出14  初始时,未读长度等于字符串长度
	var buf []byte
	buf = make([]byte, 5)
	readLen, err := r.Read(buf)
	fmt.Println("读取到的长度:", readLen) //读取到的长度5
	if err != nil {
		fmt.Println("错误:", err)
	}
	fmt.Println(buf)            //adcde
	fmt.Println(r.Len())        //9   读取到了5个 剩余未读是14-5
	fmt.Println(r.Size())       //14   字符串的长度

三、bufio.NewReader和bufio.NewWriter

cpp 复制代码
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 []byte
	buf := 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))
}
cpp 复制代码
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.File
		err 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,缓存区应该是有数值的,此时是用来读取其中的内容。

相关推荐
阿里超级工程师4 分钟前
经验分享-没有xcode也可以上传App Store Connect
xcode·上传ipa
企鹅侠客9 分钟前
Bash与Zsh与Fish:在Linux中你应该使用哪个Shell
linux·开发语言·bash·zsh·fish
RAY_010418 分钟前
Python—数据容器
开发语言·python
June bug22 分钟前
【python基础】python和pycharm的下载与安装
开发语言·python·pycharm
双叶8361 小时前
(C++)任务管理系统(正式版)(迭代器)(list列表基础教程)(STL基础知识)
c语言·开发语言·数据结构·c++·list
七七七七071 小时前
类与对象【下篇】-- 关于类的其它语法
c语言·开发语言·c++
削好皮的Pineapple!1 小时前
C语言模块化编程思维以及直流电机控制(第四天)
c语言·开发语言·单片机
im_AMBER1 小时前
python实践思路(草拟计划+方法)
开发语言·python
黄皮の电气鼠1 小时前
C++:继承
开发语言·c++·算法
rit84324992 小时前
MATLAB基于voronoi生成三维圆柱形
开发语言·人工智能·matlab