Copying data
io.Copy
reads data from a reader and writes it to a writer until one of the operations fails or the reader returns io.EOF
. There are many use cases where you need to get chunks of data from a reader and send it to a writer. io.Copy
works at an abstract layer that allows you to copy data from a file to a network connection, or from a string to a file. It also performs capability-based optimizations to minimize data copying. For instance, if the platform supports the splice system call, io.Copy
can use it to bypass buffer usage. In this section, we will see some uses of io.Copy
.
Copying files
How to do it...
To copy a file, follow these steps:
- Open the source file.
- Create the target file.
- Use
io.Copy
to copy data. - Close both files.
These steps are illustrated here:
sourceFile, err:=os.Open(sourceFileName) if err!=nil { panic(err) } defer sourceFile.Close() targetFile, err:=os.Create(targetFileName) if err!=nil { &...