After learning how to read the contents of a file in the previous article, learn how to write files.

The File output

Go provides the Create and OpenFile methods to Create files that can be written to.

  • func OpenFile(name string, flag int, perm FileMode) (*File, error)
  • func Create(name string) (*File, error)

The Create method creates or truncates a file. If the file already exists, the contents of the file are emptied, otherwise a blank file with schema 0666 is created. And the file identifier is O_RDWR can be read and written.

package main

import "fmt"
import "os"

func main (a) {
    f, err := os.Create("D:\\tmp\\f1.txt")

    iferr ! =nil {
        fmt.Printf("Error creating file, %v", err)
        return
    }
    defer f.Close()

    f.WriteString("hello go language.");
}
Copy the code

OpenFile provides a more flexible way to open files. Use flag and perm to create or open files with different permissions and modes.

package main

import "fmt"
import "os"

func main (a) {
    f, err := os.OpenFile("D:\\tmp\\f1.txt", os.O_RDWR | os.O_CREATE, 0775)

    iferr ! =nil {
        fmt.Printf("Error creating file, %v", err)
        return
    }
    defer f.Close()

    f.WriteString("This is the new text content.");
}
Copy the code

Bufio. Writer output

As mentioned in the previous article, Bufio provides Reader, Scanner, and Writer to improve file read and write efficiency. Writer is used to improve writing efficiency.

Writer contains a []byte buffer, which only writes to files when the buffer is slow. IO operations are very time consuming compared to other operations. The default buffer size in Writer is 4096 bytes, and only 4096 bytes are written to files. Of course, we can also manually flush the contents of the buffer to disk. You can also use the corresponding method to create a Writer with a buffer of the specified size.

  • Func NewWriter(w IO.Writer) *Writer Creates a Writer with a default size buffer
  • Func NewWriterSize(w IO.Writer, size int) *Writer Creates a Writer with a buffer of the specified size
  • Func (b *Writer) Flush() error Manually flushes the contents of the buffer to disk
import "fmt"
import "os"
import "bufio"

func main (a) {
    f, err := os.OpenFile("D:\\tmp\\f1.txt", os.O_RDWR | os.O_CREATE, 0775)

    iferr ! =nil {
        fmt.Printf("Error creating file, %v", err)
        return
    }
    defer f.Close()

    writer := bufio.NewWriterSize(f, 16)
    for i := 0; i<10; i++ {
        writer.WriteString("This is the new text content \n")
    }

    writer.Flush() / / 1
}
Copy the code

The code above demonstrates how to write to a file using Writer. The buffer is flushed manually at code 1 because we defined a buffer size of 16. When we last called the WriterSting method, there might still be something in the buffer that hadn’t been flushed to disk, so we’d have to flush it manually. In real programming it doesn’t matter how big the buffer is or how much has been written. We do a manual refresh at the end to prevent things from getting lost.