go 文件读写操作

 

一、读文件操作

func FileRead(path string) {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println("open file err=", err)
	}

	rb := make([]byte, 1024, 1024)

	for {
		n, err := file.Read(rb)
		if n == 0 || err == io.EOF {
			fmt.Println("jieshu")
			break
		}
		fmt.Println(string(rb[:n]))
	}

	err = file.Close()
	if err != nil {
		fmt.Println(err)
	}
}

func Bufio(path string) {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println("open file err=", err)
	}
	defer file.Close()
	/*
		const (
			defaultBufSize = 4096 //默认的缓冲区为4096
		)
	*/
	// 创建一个 *Reader ,是带缓冲区的
	reader := bufio.NewReader(file)

	// 循环读取文件的内容
	for {
		str, err := reader.ReadString('\n') //读到一个换行就结束
		if err == io.EOF {                  // io.EOF 表示文件的末尾
			break
		}
		// 输出内容,如果是用Println会多出现一个空行,Println自带换行
		fmt.Printf(str)

	}
	fmt.Println("文件读取结束!")
}

func IoUtil(path string) {
	// 使用ioutil.ReadFile 一次性将文件读取(不适合大文件操作)
	filestr, err := ioutil.ReadFile(path) // filestr类型[]byte
	if err != nil {
		fmt.Println("open file err=", err)
	}
	// 把文件内容读取到终端
	fmt.Println(string(filestr))

	// 没有打开和关闭文件句柄,因为两个操作都封装到ReadFile函数内部
}

  

  

二、写文件操作

func WriteHello(path string) {
	// 打开一个文件
	/*
			const (
		    O_RDONLY int = syscall.O_RDONLY // 只读模式打开文件
		    O_WRONLY int = syscall.O_WRONLY // 只写模式打开文件
		    O_RDWR   int = syscall.O_RDWR   // 读写模式打开文件
		    O_APPEND int = syscall.O_APPEND // 写操作时将数据附加到文件尾部
		    O_CREATE int = syscall.O_CREAT  // 如果不存在将创建一个新文件
		    O_EXCL   int = syscall.O_EXCL   // 和O_CREATE配合使用,文件必须不存在
		    O_SYNC   int = syscall.O_SYNC   // 打开文件用于同步I/O
		    O_TRUNC  int = syscall.O_TRUNC  // 如果可能,打开时清空文件
		)
	*/
	// 打开或者创建一个文件
	file, err := os.OpenFile(path, os.O_CREATE|os.O_CREATE, 0644)
	if err != nil {
		fmt.Println("open file err=", err)
	}
	defer file.Close()
	str := "hello,Sonfer!\r\n"
	// 写入时 使用带缓存的 *Writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		writer.WriteString(str)
	}
	// 因为writer是带缓存,因此调用WriterString方法时,
	// 内容先写到缓存的,所以调用Flush方法,将缓冲数据
	// 真实写入到文件中,否则文件中没有数据!
	writer.Flush()
}

func WriteAppend(path string) {
	// 打开文件时追加内容,如果是os.O_TRUNC则清空文件内容在写入
	file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open file err=", err)
	}
	defer file.Close()
	str := "追加的!\r\n"
	writer := bufio.NewWriter(file)
	for i := 0; i < 7; i++ {
		writer.WriteString(str)
	}
	writer.Flush()
}

  

  

三、将一个文件内容写入到另一个文件中

package main

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

func ReadWrite(srcpaht, despath string) {
	rdfile, err := os.Open(srcpaht)
	if err != nil {
		fmt.Println("open rdfile err=", err)
	}
	rwfile, err := os.OpenFile(despath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Println("open rwfile err=", err)
	}
	defer rdfile.Close()
	defer rwfile.Close()
	// 创建读写缓冲区
	reader := bufio.NewReader(rdfile)
	writer := bufio.NewWriter(rwfile)
	for {
		// 缓冲区中读取行数
		str, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		// 缓冲区中写文件
		writer.WriteString(str)
	}
	fmt.Println("over!")

}

func main() {
	sorfile := "G:\\GO\\1.txt"
	desfile := "G:\\GO\\2.txt"
	ReadWrite(sorfile, desfile)
}

  

 四、判断一个文件是否存在

  1. 如果返回的错误为nil,说明文件或文件夹存在
  2. 如果返回的错误类型使用os.IsNotExist()判断为true,说明文件或文件夹不存在
  3. 如果返回的错误为其它类型,则不确定是否在存在
 func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

  

五、拷贝文件

package main

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

func FileExit(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

// 编写一个拷贝函数,接收两个文件路径,源文件存在,目标文件不存在
func CopyFile(destFile, srcFile string) (written int64, err error) {
	// 判断源文件是否存在,0为随意数字
	srcfiletrue, err := FileExit(srcFile)
	if srcfiletrue == false {
		return 0, errors.New("源文件不存在!")
	}
	// 判断目标文件是否存在,0为随意数字
	destfiletrue, err := FileExit(destFile)
	if destfiletrue == true {
		return 0, errors.New("目标文件已存在!")
	}

	// 通过srcFile获取 Reader
	readfile, err := os.Open(srcFile)
	if err != nil {
		fmt.Println(err)
	}
	defer readfile.Close()
	reader := bufio.NewReader(readfile)

	//通过 destFile, 获取到 Writer
	writefile, err := os.OpenFile(destFile, os.O_RDONLY|os.O_CREATE, 0644)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer writefile.Close()
	writer := bufio.NewWriter(writefile)

	return io.Copy(writer, reader)
}

func main() {
	srcFile := "G:\\GO\\1.txt"
	destFile := "G:\\GO\\1.copy.txt"
	_, err := CopyFile(destFile, srcFile)
	if err == nil {
		fmt.Println("拷贝完成!")
	} else {
		fmt.Println("拷贝失败,err:", err)
	}

}

  

  

统计字符数量

package main

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

type CharCount struct {
	ChCount    int
	NumCount   int
	SpaceCount int
	OtherCount int
}

func main() {

	var count CharCount
	rdfile, err := os.Open("G:\\GO\\1.txt")
	if err != nil {
		fmt.Println("打开文件错误,err=", err)
		return
	}
	defer rdfile.Close()

	reader := bufio.NewReader(rdfile)

	for {
		str, err := reader.ReadString('\n')
		if err == io.EOF {
			break
		}
		fmt.Printf(str)

		for _, v := range []rune(str) {
			switch {
			case v >= 'a' && v <= 'z':
				fallthrough
			case v >= 'A' && v <= 'Z':
				count.ChCount++
			case v == '\t' || v == ' ':
				count.SpaceCount++
			case v >= '0' && v <= '9':
				count.NumCount++
			default:
				count.OtherCount++
			}

		}
	}

	fmt.Printf("字符的个数为:%v,数字的个数为:%v,空格的个数为:%v,其他字符为:%v", count.ChCount, count.NumCount, count.SpaceCount, count.OtherCount)
}

  

posted @ 2020-05-02 17:37  枯藤老艹树  阅读(1387)  评论(0编辑  收藏  举报