func main() {
var byteArr []byte
buf := bytes.NewBuffer(byteArr)
buf.Write([]byte("今天不错"))
fmt.Println(buf.String())
}
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)
}
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 字符串的长度
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))
}
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,缓存区应该是有数值的,此时是用来读取其中的内容。