GOLANG文件拷貝
在Golang中,使用系統自帶函數io.Copy()
如:
- srcFile := "C:/Users/Wisdom/Desktop/Wisdompic.png" (源文件)
- dstFile := "C:/Users/Wisdom/Desktop/Ouxiaobaicopy.png" (目標文件)
將srcFile文件打開並讀取到系統內存中,並將讀取的內容拷貝到dstFile 路徑下,完成拷貝操作!
package main import( "fmt" "os" "io" "bufio" ) func CopyFile (dstFilePath string,srcFilePath string)(written int64, err error){ srcFile,err := os.Open(srcFilePath) if err != nil{ fmt.Printf("打開源文件錯誤,錯誤信息=%v\n",err) } defer srcFile.Close() reader := bufio.NewReader(srcFile) dstFile,err := os.OpenFile(dstFilePath,os.O_WRONLY | os.O_CREATE,0777) if err != nil{ fmt.Printf("打開目標文件錯誤,錯誤信息=%v\n",err) return } writer := bufio.NewWriter(dstFile) defer dstFile.Close() return io.Copy(writer,reader) } func main (){ srcFile := "C:/Users/Wisdom/Desktop/Wisdompic.png" dstFile := "C:/Users/Wisdom/Desktop/Ouxiaobaicopy.png" _, err :=CopyFile(dstFile,srcFile) if err == nil { fmt.Printf("完成拷貝,Done\n") }else{ fmt.Printf("未完成拷貝,錯誤=%v\n",err) } }