GO实践二:读写文件

233 阅读1分钟

文件读写是很多场景遇到的问题,本文主要围绕GO如何完成读写进行整理总结

读文件

按行读

func ReadFileByLine() {
	pwd, err := os.Getwd()
	if err != nil {
		return
	}
	filepath := path.Join(pwd, "txt")

	inputFile, inputError := os.Open(filepath)
	if inputError != nil {
		log.Println(inputError)
		return
	}
	defer inputFile.Close()

	inputReader := bufio.NewReader(inputFile)
	for {
	    // 注释的方法也可用
		//inputStr, readError := inputReader.ReadString('\n')
		//if readError == io.EOF {
		//	return
		//}
		//fmt.Print(inputStr)
		inputStr, _, readError := inputReader.ReadLine()
		if readError != nil {
			return
		}
		fmt.Println(string(inputStr))
	}
}

全部读

func ReadFileAll() {
	pwd, err := os.Getwd()
	if err != nil {
		log.Println(err)
	}
	filePath := path.Join(pwd, "txt")
	inputFile, inputError := ioutil.ReadFile(filePath)
	if inputError != nil {
		log.Println(inputError)
		return
	}
	fmt.Print(string(inputFile))
}

按块读

func readFileByBlock() {
	f, err := os.Open("txt")
	if err != nil {
		log.Println(err)
	}
	defer f.Close()
	cat(f)

}
func cat(f *os.File) {
	const NBUF = 512
	var buf [NBUF]byte
	for {
		switch nr, er := f.Read(buf[:]); true {
		case nr < 0:
			fmt.Fprintf(os.Stderr, "cat: error reading from %s: %s\n",
				f.Name(), er)
			os.Exit(1)
		case nr == 0: // EOF
			return
		case nr > 0:
			if nw, ew := os.Stdout.Write(buf[0:nr]); nw != nr {
				fmt.Fprintf(os.Stderr, "cat: error writing from %s: %s\n",
					f.Name(), ew)
			}
		}
	}
}

全部写

func WriteFile() {
	str := "hello world"
	pwd, err := os.Getwd()
	if err != nil {
		log.Println(err)
	}
	filePath := path.Join(pwd, "txt1")
	outputError := ioutil.WriteFile(filePath, []byte(str), 0666)
	if outputError != nil {
		log.Println(outputError)
	}
	return
}

追加写

func WriteFileAppend() {
	str := "hello world\n"
	pwd, err := os.Getwd()
	if err != nil {
		log.Println(err)
	}
	filePath := path.Join(pwd, "txt1")

	file, err := os.OpenFile(filePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		log.Println(err)
		return
	}
	defer file.Close()

	writer := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		count, _ := writer.WriteString(str)
		fmt.Println(count)
	}

	writer.Flush()
}

COPY

func CopyFile() {
	pwd, err := os.Getwd()
	if err != nil {
		log.Println(err)
	}
	srcPath := path.Join(pwd, "txt")
	dstPath := path.Join(pwd, "txt2")

	srcFile, err := os.Open(srcPath)
	if err != nil {
		log.Println(err)
		return
	}
	defer srcFile.Close()

	//dstFile,err:=os.OpenFile(dstPath,os.O_WRONLY|os.O_CREATE,0666)
	dstFile, err := os.Create(dstPath)
	if err != nil {
		log.Println(err)
		return
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		log.Println(err)
	}
}