Writing Files {.en}

写文件 {.zh}

::: {.en} Writing files in Go follows similar patterns to the ones we saw earlier for reading. :::

::: {.zh}

在Go中编写文件的方式与我们之前看到的用于阅读的模式类似。

:::

  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. )
  8. func check(e error) {
  9. if e != nil {
  10. panic(e)
  11. }
  12. }
  13. func main() {

::: {.en} To start, here’s how to dump a string (or just bytes) into a file. :::

::: {.zh}

首先,这里是如何将字符串(或justbytes)转储到文件中。

:::

  1. d1 := []byte("hellongon")
  2. err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
  3. check(err)

::: {.en} For more granular writes, open a file for writing. :::

::: {.zh}

要进行更精细的写入,请打开文件进行写入。

:::

  1. f, err := os.Create("/tmp/dat2")
  2. check(err)

::: {.en} It’s idiomatic to defer a Close immediately after opening a file. :::

::: {.zh}

打开文件后立即推迟“关闭”是惯用的。

:::

  1. defer f.Close()

::: {.en} You can Write byte slices as you’d expect. :::

::: {.zh}

您可以按照预期“写”字节切片。

:::

  1. d2 := []byte{115, 111, 109, 101, 10}
  2. n2, err := f.Write(d2)
  3. check(err)
  4. fmt.Printf("wrote %d bytesn", n2)

::: {.en} A WriteString is also available. :::

::: {.zh}

WriteString也可用。

:::

  1. n3, err := f.WriteString("writesn")
  2. fmt.Printf("wrote %d bytesn", n3)

::: {.en} Issue a Sync to flush writes to stable storage. :::

::: {.zh}

发出“同步”以刷新写入稳定存储。

:::

  1. f.Sync()

::: {.en} bufio provides buffered writers in addition to the buffered readers we saw earlier. :::

::: {.zh}

bufio除了我们之前看到的缓冲读卡器外,还提供缓冲写入器。

:::

  1. w := bufio.NewWriter(f)
  2. n4, err := w.WriteString("bufferedn")
  3. fmt.Printf("wrote %d bytesn", n4)

::: {.en} Use Flush to ensure all buffered operations have been applied to the underlying writer. :::

::: {.zh}

使用Flush确保所有缓冲操作都已应用于底层writer。

:::

  1. w.Flush()
  2. }

::: {.en} Try running the file-writing code. :::

::: {.zh}

尝试运行文件编写代码。

:::

  1. $ go run writing-files.go
  2. wrote 5 bytes
  3. wrote 7 bytes
  4. wrote 9 bytes

::: {.en} Then check the contents of the written files. :::

::: {.zh}

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

:::

  1. $ cat /tmp/dat1
  2. hello
  3. go
  4. $ cat /tmp/dat2
  5. some
  6. writes
  7. buffered

::: {.en} Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams. :::

::: {.zh}

接下来我们将看看我们刚刚看到的一些文件I / O想法应用于stdinstdout流。

:::