go语言文件的写入操作 Write和WriteString bufio.NewWriter ioutil.WriteFile

go语言文件的写入操作 Write和WriteString bufio.NewWriter ioutil.WriteFile_第1张图片

文件的写入操作

  • Write和WriteString
  • bufio.NewWriter
  • ioutil.WriteFile

Write和WriteString

bufio.NewWriter

ioutil.WriteFile

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()

}

你可能感兴趣的:(GO,语言基础)