In Go, handling file I/O primarily involves several core packages: os, bufio, and ioutil. Below, I will cover the main usage of these packages and provide practical code examples.
1. Using the os Package
The os package provides fundamental file operations, including opening, reading, writing, and closing files.
Opening a File:
gofile, err := os.Open("filename.txt") if err != nil { // Error handling log.Fatal(err) } defer file.Close()
Here, os.Open is used for reading operations. For writing operations, you can use os.Create or os.OpenFile.
Reading a File:
godata := make([]byte, 100) // Allocate a buffer count, err := file.Read(data) if err != nil { // Error handling log.Fatal(err) } fmt.Println("Number of bytes read: ", count) fmt.Println("Data content: ", string(data))
Writing to a File:
godata := []byte("hello, world\n") count, err := file.Write(data) if err != nil { // Error handling log.Fatal(err) } fmt.Println("Number of bytes written: ", count)
2. Using the bufio Package
The bufio package offers buffered reading and writing capabilities, wrapping the os.File object for more efficient operations.
Create a Buffered Reader:
goreader := bufio.NewReader(file) line, err := reader.ReadString('\n') if err != nil && err != io.EOF { // Error handling log.Fatal(err) } fmt.Println("Read data: ", line)
Create a Buffered Writer:
gowriter := bufio.NewWriter(file) bytesWritten, err := writer.WriteString("Hello, Gophers!\n") if err != nil { log.Fatal(err) } writer.Flush() // Ensure all buffered data is written to the underlying io.Writer fmt.Println("Number of bytes written: ", bytesWritten)
3. Using the ioutil Package
Although most functionalities of the ioutil package have been integrated into os or io since Go 1.16, it was commonly used in earlier versions to simplify file read/write operations.
Read the Entire File:
godata, err := ioutil.ReadFile("filename.txt") if err != nil { log.Fatal(err) } fmt.Println("File content: ", string(data))
Write the Entire File:
goerr := ioutil.WriteFile("filename.txt", data, 0644) if err != nil { log.Fatal(err) }
Summary
These are the primary methods for handling file I/O in Go. By combining os, bufio, and (in older Go versions) ioutil, you can flexibly perform various file operations. In daily development, selecting the appropriate method depends on specific requirements, such as whether efficient buffered reading/writing is needed or simple one-time read/write operations.