5.1. Input/Output
Basics
| |
Output:
Hello, file system
Reader/Writer
The above example of reading a file loads the whole file into memory. This can cause problems when we are dealing with large files. To solve this problem, we can load chunks of data and place them into a buffer.
The Go standard library provides the Reader and Writer interface for reading and writing data in a streaming fashion. The various reader and writer implementations are then often used together with the primitives from the io package (e.g. io.Copy ).
The io.Writer interface expects a slice of bytes and returns the amount of bytes that were written and an error.
type Writer interface {
Write(p []byte) (n int, err error)
}
The io.Reader interface expects an byte slice. This slice is used as a buffer. It returns the amount of bytes that were read and an error.
type Reader interface {
Read(p []byte) (n int, err error)
}
Here is an example were we copy data from a bytes.Buffer to a file (os.File ). We create the buffer from a string using bytes.NewBufferString . Then we open the file with os.Create . With io.Copy we copy all bytes from the buffer to the file.
| |
Output:
17 bytes written