go语言实现文件的读写和拷贝

package file_utils

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)
// 打开文件
func OpenFile(filePath string)  {
	file,err:=os.Open(filePath)

	if err==nil{
		fmt.Println("该文件不为空")
	}else{
		fmt.Println(filePath,"不存在!")
	}

	fmt.Println(file)
	err=file.Close()
	if err==nil{
		fmt.Println(filePath,"已经关闭!")
	}
}

//普通方式读取文件
func ReadFileContent(filePath string)  {
	file,err:=os.Open(filePath)

	if err!=nil{
		fmt.Println("该文件不存在")
	}
	//必须关闭(否则可能有内存泄漏问题),defer修饰的代码块最后执行
	defer
	file.Close();
    //使用缓冲区读取文件,缓冲区大小设置为1024个字节
    buffer:=make([]byte,1024,1024)
    //通过bufio和file创建Reader对象
    reader:=bufio.NewReader(file)
    for{
		n, err := reader.Read(buffer)
		if n==0|| err==io.EOF{
			break
		}
    	fmt.Println(string(buffer))
	}
}


//使用ioutil读取文件,可以不显式创建file对象,也不需要显示close文件。
//不用创建缓冲区读取文件,但这种方式只适用于文件比较小的情况
func ReadFileByIOUtil(filePath string)  {
	content, err := ioutil.ReadFile(filePath)
	if(err!=nil){
		fmt.Println(err)
	}
	//字节切片转换为字符串
	fmt.Println(string(content))
}

//创建新文件并写入数据
func CreateFileAndWrite(filePath string)  {
	//第一个参数表示文件路径,第二个参数表示操作模式(这里是只写模式和创建模式),第三个参数是linux下的文件权限
	file, e := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0777)
	if(e!=nil){
		fmt.Println(e)
		return
	}
	//最后关闭文件
	defer file.Close()

	str:="A fellow doesn't last long on what he has done. He's got to keep on delivering as he goes along."

	writer:=bufio.NewWriter(file)

	writer.WriteString(str)
	//因为write带缓存,使用Flush方法才能将数据写入到文件
	writer.Flush()
}

// 使用copy函数完成文件拷贝(也可以使用io包下的Read()和Write()方法实现)
func CopyFile(srcFilePath string,destFilePath string,)(int64,error)  {
	srcFile, srcErr := os.Open(srcFilePath)
	if(srcErr!=nil){
		return 0,srcErr
	}
	destFile, destE := os.OpenFile(destFilePath, os.O_WRONLY|os.O_CREATE, 0777)
	if(destE!=nil){
		return 0,destE
	}

	//关闭文件
	defer  srcFile.Close()
	defer  destFile.Close()

	//使用copy函数完成拷贝功能
	return io.Copy(destFile,srcFile)
}
//使用IOUtil完成文件的复制功能
//使用ioutil不用显式地关闭文件
func CopyFileByUtil(srcFilePath string,destFilePath string,)(int,error)  {
	input, srcErr := ioutil.ReadFile(srcFilePath)

	if(srcErr!=nil){
		fmt.Println(srcErr)
		return 0,srcErr
	}

	err := ioutil.WriteFile(destFilePath, input, 0666)
	if(err!=nil){
		fmt.Println(err)
		return 0,err
	}

	return len(input),nil
}

 

主函数:      

package main

import "com/baidu/file/file_utils"

func main() {
	//file_utils.Test("1111")
	//file_utils.OpenFile("d:/hello.txt")
	//file_utils.ReadFileContent("d:/hello.txt")
	//file_utils.ReadFileByIOUtil("d:/hello.txt");
	//file_utils.CreateFileAndWrite("d:/test.txt")
	//file_utils.CopyFile("d:/test.txt","d:/testCopy.txt")
	file_utils.CopyFileByUtil("d:/test.txt","d:/testCopyByUtil.txt")
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值