bufio 包提供的缓冲读取(buffered reader)来读取数据

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. var inputReader *bufio.Reader
  8. func main() {
  9. inputReader = bufio.NewReader(os.Stdin)
  10. fmt.Println("please enter some input:")
  11. input, err := inputReader.ReadString('\n')
  12. if err == nil {
  13. fmt.Printf("The input was: %s\n", input)
  14. }
  15. }
  16. > go run main.go
  17. please enter some input:
  18. 1111
  19. The input was: 1111

读取文件

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "os"
  7. )
  8. func main() {
  9. inputFile, inputError := os.Open("nginx.conf")
  10. if inputError != nil {
  11. fmt.Println("An error occurred on opening the inputfile", inputError)
  12. return
  13. }
  14. defer inputFile.Close()
  15. inputReader := bufio.NewReader(inputFile)
  16. for {
  17. inputString, readerError := inputReader.ReadString('\n')
  18. fmt.Printf(inputString)
  19. if readerError == io.EOF {
  20. return
  21. }
  22. }
  23. }

写入文件

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)
  9. if outputError != nil {
  10. fmt.Printf("An error occurred with file opening or creating or creation \n")
  11. return
  12. }
  13. defer outputFile.Close()
  14. outputWriter := bufio.NewWriter(outputFile)
  15. outputString := "hello world!!\n"
  16. for i := 0; i < 10; i++ {
  17. outputWriter.WriteString(outputString)
  18. }
  19. outputWriter.Flush()
  20. }