# 08.9 写入文件

一般来说，你可以使用`io.Writer`接口将数据写入磁盘上的文件。然而，`save.go`代码将向你展示五种将数据写入文件的方法。`save.go`程序分为六部分。

`save.go`第一部分代码如下：

```go
package main

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

`save.go` 第二部分代码如下：

```go
func main() {
    s := []byte("Data to write\n")

    f1, err := os.Create("f1.txt")
    if err != nil {
        fmt.Println("Cannot create file", err)
        return
    }
    defer f1.Close()
    fmt.Fprintf(f1, string(s))
```

注意，在这个`Go`程序中涉及到写入的每一行都将使用`s`字节切片。此外，`fmt.Fprintf()`函数可以帮助你使用所需的格式将数据写入自己的日志文件。在本例中，`fmt.Fprintf()`将数据写入`f1`标识的文件。

`save.go` 第三部分代码如下：

```go
    f2, err := os.Create("f2.txt")
    if err != nil {
        fmt.Println("Cannot create file", err)
        return
    }
    defer f2.Close()
    n, err := f2.WriteString(string(s))
    fmt.Printf("wrote %d bytes\n", n)
```

其中，`f2.WriteString()`用于将数据写入文件。

`save.go` 第四部分代码如下：

```go
    f3, err := os.Create("f3.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    w := bufio.NewWriter(f3)
    n, err = w.WriteString(string(s))
    fmt.Printf("wrote %d bytes\n", n)
    w.Flush()
```

其中，`bufio.NewWriter()`打开文件，并调用`bufio.WriteString()`写入数据。

`save.go` 第五部分代码将教你写入文件的其他方法：

```go
    f4 := "f4.txt"
    err = ioutil.WriteFile(f4, s, 0644)
    if err != nil {
        fmt.Println(err)
        return
    }
```

此方法只需要简单调用`ioutil.WriteFile()`函数，而无需使用`os.Create()`。

`save.go` 最后一部分代码如下：

```go
    f5, err := os.Create("f5.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    n, err = io.WriteString(f5, string(s))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Printf("wrote %d bytes\n", n)
}
```

该技术使用`io.WriteString()`将所需数据写入文件。

执行`save.go`将产生如下的输出：

```
$ go run save.go 
wrote 14 bytes
wrote 14 bytes
wrote 14 bytes
$ ls -l f?.txt
-rw-r--r--  1 mtsouk  staff  14  Jan  23 20:30 f1.txt
-rw-r--r--  1 mtsouk  staff  14  Jan  23 20:30 f2.txt
-rw-r--r--  1 mtsouk  staff  14  Jan  23 20:30 f3.txt
-rw-r--r--  1 mtsouk  staff  14  Jan  23 20:30 f4.txt
-rw-r--r--  1 mtsouk  staff  14  Jan  23 20:30 f5.txt
$ cat f?.txt
Data to write
Data to write
Data to write
Data to write
Data to write
```

下一节将向你展示如何通过`Go`标准库中的专用包功能将数据保存到文件中。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wskdsgcf.gitbook.io/mastering-go-zh-cn/08.0/08.9.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
