package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func writeByte(path, str string) {
fileObj, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 132)
if err != nil {
fmt.Println(err)
return
}
defer func() {
err := fileObj.Close()
if err != nil {
fmt.Println(err)
}
}()
n, err := fileObj.WriteString(str)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("这个N是干嘛的: %v", n)
//fileObj.WriteString(str)
//fileObj.Write([]byte(str))
}
func appendWrite(filePath string, input string) {
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
file, err = os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
}
//及时关闭file句柄
defer func(file *os.File) {
err := file.Close()
if err != nil {
}
}(file)
//写入文件时,使用带缓存的 *Writer
write := bufio.NewWriter(file)
_, err1 := write.WriteString(input + "\r\n")
if err1 != nil {
return
}
//Flush将缓存的文件真正写入到文件中
err2 := write.Flush()
if err2 != nil {
return
}
}
func writeBufio(path, str string) {
fileObj, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 132)
if err != nil {
fmt.Println(err)
return
}
defer func() {
err := fileObj.Close()
if err != nil {
fmt.Println(err)
}
}()
write := bufio.NewWriter(fileObj)
// 此时写在了缓存中
write.Write([]byte(str))
// 需要从缓存中写入到文件
err1 := write.Flush()
if err1 != nil {
fmt.Println(err1)
}
}
func writeIoutil(path, str string) {
err := ioutil.WriteFile(path, []byte(str), 123)
if err != nil {
fmt.Println(err)
return
}
}
func main() {
path := "./writetest.txt"
writeStr := "张三说\n我摸你是你的福气\n我就摸你了\n咋滴啦 咋滴啦"
// 转字节写入
//writeByte(path, writeStr)
// bufio写入
//writeBufio(path, writeStr)
// ioutil写入
writeIoutil(path, writeStr)
}