初学GoLang,拷贝文件

如需执行需要进入到该文件所在的目录,然后运行如下命令:

go run File.go

代码如下:

package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

// CopyFile destPath 目标文件路径 srcPath 源文件路径
func CopyFile(destPath string, srcPath string) (written int64, err error) {
	srcFile, err := os.Open(srcPath)
	if err != nil {
		fmt.Println("打开源文件失败")
	}
	// 关闭流 defer关键字表示该函数结束时调用
	defer srcFile.Close()
	// 打开目标文件 以可写和不存在就创建的方式打开
	destFile, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Println("打开目标文件失败")
	}
	// 关闭流 defer关键字表示该函数结束时调用
	defer destFile.Close()
	return io.Copy(bufio.NewWriter(destFile), bufio.NewReader(srcFile))
}

func main() {
	// 源文件
	srcPath := "/Users/anran/Downloads/test_create.txt"
	// 目标文件
	destPath := "/Users/anran/Downloads/test_create_copy.txt"

	// 调用拷贝文件函数
	_, err := CopyFile(destPath, srcPath)

	if err == nil {
		fmt.Println("文件复制成功")
	} else {
		fmt.Println("文件复制失败,err=%v", err)
	}
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇