GOLANG文件拷貝


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)
	}
}

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM