在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
实例1 //main package main import ( "bufio" "flag" "fmt" "io" "os" "strings" ) func fileExists(filename string) bool { _, err := os.Stat(filename) return err == nil || os.IsExist(err) } func copyFile(src, dst string) (w int64, err error) { srcFile, err := os.Open(src) if err != nil { fmt.Println(err.Error()) return } defer srcFile.Close() dstFile, err := os.Create(dst) if err != nil { fmt.Println(err.Error()) return } defer dstFile.Close() return io.Copy(dstFile, srcFile) } func copyFileAction(src, dst string, showProgress, force bool) { if !force { if fileExists(dst) { fmt.Printf("%s exists override? y/n\n", dst) reader := bufio.NewReader(os.Stdin) data, _, _ := reader.ReadLine() if strings.TrimSpace(string(data)) != "y" { return } } } copyFile(src, dst) if showProgress { fmt.Printf("'%s'->'%s'\n", src, dst) } } func main() { var showProgress, force bool
示例2:Golang实现文件拷贝功能 package main import ( "bufio" "fmt" "io" "os" ) // 编写一个函数,接收两个文件路径: func copyFile(dstFileName string, srcFileName string) (written int64, err error) { srcFile, err := os.Open(srcFileName) if err != nil { fmt.Printf("open file error = %v\n", err) } defer srcFile.Close() //通过srcFile,获取到READER reader := bufio.NewReader(srcFile) //打开dstFileName dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Printf("open file error = %v\n", err) return } //通过dstFile,获取到WRITER writer := bufio.NewWriter(dstFile) //writer.Flush() defer dstFile.Close() return io.Copy(writer, reader) } func main() { //调用copyFile完成文件拷贝 srcFile := "e:/copyFileTest02.pdf" dstFile := "e:/Go/tools/copyFileTest02.pdf" _, err := copyFile(dstFile, srcFile) if err == nil { fmt.Println("拷贝文件正常...") } else { fmt.Printf("拷贝文件出错了... err =%v\n", err) } } 说明: 1, 使用了带缓存的 bufio.NewReader(srcFile) 和 bufio.NewWriter(dstFile),一边读一边写,这样支持拷贝较大的文件;
|
请发表评论