1.使用io包:
func ioCopy(srcName , distName string) (error){
srcFile ,err := os.Open(srcName)
if err != nil {
return err
}
defer srcFile.Close()
distFile , err := os.Create(distName)
if err != nil {
return err
}
defer distFile.Close()
_ , err = io.Copy(distFile,srcFile)
return err
}
2.使用os包循環(huán)遍歷讀取寫入:
func osReader(srcName , distName string) (error){
srcFile ,err := os.Open(srcName)
if err != nil {
return err
}
defer srcFile.Close()
distFile , err := os.Create(distName)
if err != nil {
return err
}
defer distFile.Close()
buf := make([]byte,1024*4)
for {
n ,err := srcFile.Read(buf)
distFile.Write(buf[:n])
if err != nil {
if err == io.EOF {
break
}
return err
}
}
return nil
}
3.使用ioutil包:
func ioutilWriteFile(srcName , distName string) (error){
copyBytes , err := ioutil.ReadFile(srcName)
if err != nil {
return err
}
return ioutil.WriteFile(distName,copyBytes,0644)
}