gobyexample-writing-files

来源:https://github.com/xg-wang/gobyexample/tree/master/examples

package main

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

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

func main() {

    //写入一个字符串(或者只是一些字节)到一个文件
    d1 := []byte("hello\ngo\n")
    err := ioutil.WriteFile("D:/goworkspace/src/gobyexample/writing-files/dat1.txt", d1, 0644)
    check(err)

    //对于更细粒度的写入,先打开一个文件
    f, err := os.Create("D:/goworkspace/src/gobyexample/writing-files/dat2.txt")
    check(err)

    //打开文件后,习惯立即使用 defer 调用文件的`Close`操作
    defer f.Close()

    //可以写入字节切片
    d2 := []byte{115, 111, 109, 101, 10} //some\n
    n2, err := f.Write(d2)
    check(err)
    fmt.Printf("wrote %d bytes\n", n2)

    n3, err := f.WriteString("writes\n")
    fmt.Printf("wrote %d bytes\n", n3)

    //调用 `Sync` 来将缓冲区的信息写入磁盘
    f.Sync()

    w := bufio.NewWriter(f)
    n4, err := w.WriteString("buffered\n")
    fmt.Printf("wrote %d bytes\n", n4)

    //使用`Flush`来确保所有缓存的操作已写入底层写入器
    w.Flush()
}

输出结果

wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
![image.png](https://upload-images.jianshu.io/upload_images/7547037-f5abc353c62959cd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![image.png](https://upload-images.jianshu.io/upload_images/7547037-6c2ea3d0a66266e7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

你可能感兴趣的:(gobyexample-writing-files)