package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func writeDemo1() {
fileObj, err := os.OpenFile("./writeDemo1", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 5656)
if err != nil {
fmt.Printf("open file failed,err:%v", err)
return
}
defer fileObj.Close()
fileObj.WriteString("你好 世界")
fileObj.Write([]byte("你好 China"))
}
func writeDemo2() {
fileObj, err := os.OpenFile("./writeDemo2", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
fmt.Printf("open file failed,err:%v", err)
return
}
defer fileObj.Close()
//创建一个往文件里写的对象
writer := bufio.NewWriter(fileObj)
writer.WriteString("你好 世界") //写到了缓存
writer.Flush() //将缓存中的内容写到文件里
}
func writeDemo3() {
//先定义好一个字符串
str := "writeDemo3()"
//写入文件
err := ioutil.WriteFile("./writeDemo3", []byte(str), 564)
//写入文件出错
if err != nil {
fmt.Printf("write file failed,err:%v", err)
return
}
}
func main() {
fmt.Println("-------------------------------Write和WriteString------------------------------")
writeDemo1()
fmt.Printf("-------------------------------------bufio.NewWriter---------------------")
writeDemo2()
fmt.Printf("-------------------------------------bufio.NewWriter---------------------")
writeDemo3()
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)