Golang Copy FileUse ioutil to copy a file by reading in its contents and then writing to a new file.
Copy file. In Golang the os.Rename func moves a file from one location to another. But if we want to copy the file, we cannot just move it.
With ioutil, we can read in the contents of a file (with ReadAll). Then we can write the copy to a new location. This logic can be placed in a reusable func.
Copy example. Here we have a main func that begins with 2 local variables. We must specify a valid input path (the source) and output path (the target).
Part 1 We open an input file with the os.Open func. We just ignore errors, but these could be checked.
Part 2 We read in the data from the file with ioutil.ReadAll. Again we just ignore errors.
Part 3 We call ioutil.WriteFile to write the data to a new location—the target location for the copy.
Golang program that copies file
package main import ( "fmt" "io/ioutil" "os" ) func main() { inputPath := `C:\programs\file.txt` outputPath := `C:\programs\copy.txt` // Part 1: open input file. inputFile, _ := os.Open(inputPath) // Part 2: call ReadAll to get contents of input file. data, _ := ioutil.ReadAll(inputFile) // Part 3: write data to copy file. ioutil.WriteFile(outputPath, data, 0) fmt.Println("DONE") }
Notes, copying. When we want to copy a file, we cannot just call os.Rename as the original is deleted. Instead, we can use helpful methods from ioutil.
Test data:
file.txt: 60 bytes copy.txt: 60 bytes
A summary. Often it is important to copy files for deployment of projects (like websites or applications). With the code here, we can copy files without deleting the originals.
© 2007-2021 sam allen. see site info on the changelog