[TOC] ## ReadByte 只获取一个 字符 ``` reader := bufio.NewReaderSize(strings.NewReader("http://studygolang.com.\nt It is the home of gophers"), 14) s, _ := reader.ReadByte() fmt.Println(string(s)) //h ``` ## ReadBytes 截取到界定符 ``` reader := bufio.NewReaderSize(strings.NewReader("http://studygolang.com.\nt It is the home of gophers"), 14) s, _ := reader.ReadBytes('\n') fmt.Println(string(s)) //h ``` ## ReadString ``` reader := bufio.NewReaderSize(strings.NewReader("http://studygolang.com.\nt It is the home of gophers"), 14) s, _ := reader.ReadString('\n') fmt.Println(s) //http://studygolang.com. s, e := reader.ReadString('\n') fmt.Println(e) //EOF fmt.Println(s) //http://studygolang.com. ``` ## Peek 窥探下次要去的数据 > 只是“窥探”一下Reader中没有读取的n个字节。好比栈数据结构中的取栈顶元素,但不出栈 ``` reader := bufio.NewReaderSize(strings.NewReader("http://studygolang.com.\nt It is the home of gophers"), 14) bytes, _ := reader.Peek(2) fmt.Println(string(bytes)) //ht s, _ := reader.ReadString('\n') //http://studygolang.com. fmt.Println(s) ``` ## NewScanner 读取屏幕输入 ``` scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { fmt.Println(scanner.Text()) // Println will add back the final '\n' } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading standard input:", err) } ``` ## 进行分词 ``` const input = "This is The Golang 你好 Standard Library.\nWelcome you!" scanner := bufio.NewScanner(strings.NewReader(input)) //scanner.Split(bufio.ScanBytes) //单个词分词.不能分中文 //scanner.Split(bufio.ScanLines) //以行分词 //scanner.Split(bufio.ScanRunes) //以词分词,可分中文 scanner.Split(bufio.ScanWords) //以空格分词 count := 0 for scanner.Scan() { fmt.Println(scanner.Text()) count++ } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } fmt.Println(count) ```