Use the io.Copy function to copy data from the source Reader to the target Writer
In the Go language, we often encounter situations where we need to copy a data stream from one place to another. In order to simplify this process, Go language provides a very convenient function io.Copy.
io.Copy function is defined as follows:
func Copy(dst Writer, src Reader) (written int64, err error)
This function receives two parameters, respectively. Is the target Writer and source Reader. It will read the data in the source Reader one by one and write it to the target Writer until all the data in the source Reader is copied. The function will return an int64 type value, indicating the number of bytes copied successfully, as well as any errors that may have occurred.
Let’s look at a specific usage example.
package main
import (
"fmt" "io" "os"
)
func main() {
sourceFile, err := os.Open("source.txt") if err != nil { fmt.Println("打开源文件失败:", err) return } defer sourceFile.Close() destFile, err := os.Create("dest.txt") if err != nil { fmt.Println("创建目标文件失败:", err) return } defer destFile.Close() written, err := io.Copy(destFile, sourceFile) if err != nil { fmt.Println("复制文件失败:", err) return } fmt.Printf("成功复制了%d个字节的数据
", written)
}
In the above code, we first opened a source file through the os.Open function, and then created a target file through the os.Create function. Then, we passed the source file and the target file into io respectively. The .Copy function performs a copy operation. Finally, we output the number of bytes successfully copied.
Readers can modify the code according to their own needs, such as replacing the paths of the source and target files, or doing other Data operations.
It should be noted that the io.Copy function will have some buffer operations, so it may consume more memory when copying large files. If you need to copy large files, it is recommended to use io. CopyBuffer function to set a custom buffer size.
Summary:
By using the io.Copy function, we can easily copy a data stream from one place to another. It reduces our Manually handle the data copying work yourself to make the code more concise and efficient. I hope the sample code in this article can help readers better understand and use the io.Copy function.
The above is the detailed content of Use the io.Copy function to copy data from source Reader to target Writer. For more information, please follow other related articles on the PHP Chinese website!