Similar to Golang-reading files , Go can implement file writing operations through os
or packages. ioutil
Writing a file is generally done by returning a structure os
through Open
or a function , and then performing a write operation through the built-in function. The essence of adopting is also to use writing files, but it only makes a layer of encapsulation.Create
File
File
ioutil
os
Opens a file via os.Open
a function, returning an error if the file does not exist.
Create a file through os.Create
the function, and clear the file content if the file already exists.
Writing files is based on []byte
the operations performed, and you need to understand string
and []byte
convert operations in advance.
b := []byte("ABC€")
fmt.Println(b) // [65 66 67 226 130 172]
s := string([]byte{
65, 66, 67, 226, 130, 172})
fmt.Println(s) // ABC€
The following is a specific example, and the key codes have corresponding comments
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func main() {
WriteByIoUtil("H:\\go\\main\\2.txt")
WriteByOs("H:\\go\\main\\3.txt")
}
func WriteByIoUtil(filename string) {
d := []byte("hello\ngo\n")
err := ioutil.WriteFile(filename, d, 0644)
CheckErr(err)
}
func WriteByOs(filename string) {
f, err := os.Create(filename)
CheckErr(err)
defer f.Close()
//通过f.Write函数写文件
d2 := []byte("some\n")
n2, err := f.Write(d2)
CheckErr(err)
fmt.Printf("wrote %d bytes\n", n2)
//通过f.WriteString函数写文件
n3, err := f.WriteString("writes\n")
CheckErr(err)
fmt.Printf("wrote %d bytes\n", n3)
f.Sync()
//通过bufio提供的Writer.WriteString函数写文件
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
CheckErr(err)
fmt.Printf("wrote %d bytes\n", n4)
w.Flush()
}
func CheckErr(e error) {
if e != nil {
panic(e)
}
}