Go by Example 中文版: 写文件

时间:2022-07-25
本文章向大家介绍Go by Example 中文版: 写文件,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Go by Example 中文版:写文件

在 Go 中,写文件与我们前面看过的读文件方法类似。

对应的Go语言代码示例如下:

//Go by Example 中文版: 写文件
//https://gobyexample-cn.github.io/writing-files
//在 Go 中,写文件与我们前面看过的读文件方法类似。

package main

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

func check(e error) {
	if e != nil {
		panic(e)
	}
}

func main() {
	//开始!这里展示了如何写入一个字符串(或者只是一些字节)到一个文件。
	d1 := []byte("hellongon")
	err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
	check(err)

	//对于更细粒度的写入,先打开一个文件。
	f, err := os.Create("/tmp/dat2")
	check(err)
	//打开文件后,一个习惯性的操作是:立即使用defer调用文件的Close。
	defer f.Close()

	//您可以按期望的那样 Write 字节切片。
	d2 := []byte{115, 111, 109, 101, 10}
	n2, err := f.Write(d2)
	check(err)
	fmt.Printf("wrote %d bytesn", n2)

	//WriteString也是可用的。
	n3, err := f.WriteString("writesn")
	fmt.Printf("wrote %d bytesn",n3)

	//调用Sync将缓冲区中的数据写入硬盘。
	f.Sync()

	//与我们前面看到的带缓冲的 Reader 一样,bufio 还提供了的带缓冲的 Writer。
	w := bufio.NewWriter(f)
	n4, err := w.WriteString("bufferedn")
	check(err)
	fmt.Printf("wrote %d bytesn",n4)

	//使用 Flush 来确保,已将所有的缓冲操作应用于底层 writer。
	w.Flush()
}

运行这段文件写入代码。

$ go run writing-files.go 
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

然后检查写入文件的内容。

$ cat /tmp/dat1
hello
go
$ cat /tmp/dat2
some
writes
buffered

我在CentOS7下的运行结果如下图所示:

我们刚刚看到了文件 I/O 思想, 接下来,我们看看它在 stdin 和 stdout 流中的应用。