go文件操作练习

package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func readAll() {
	//打开文件
	fileObj, err := os.Open("./xx.txt")

	if err != nil {
		fmt.Printf("open file failed,err:%v\n", err)
		return
	}
	//关闭文件
	defer fileObj.Close()

	for {
		var tmp = make([]byte, 128)
		n, err := fileObj.Read(tmp)
		if err == io.EOF {
			//当前读了多少字节打印出来 然后退出
			fmt.Printf(string(tmp[:n]))
			return
		}
		if err != nil {
			fmt.Printf("read form file failed,err:%v\n", n)
		}
		fmt.Printf("read %d bytes from file . \n", n)
		fmt.Println(string(tmp[:n]))
	}
}
func readByBufio() {
	//打开文件
	fileObj, err := os.Open("./xx.txt")
	if err != nil {
		fmt.Printf("open file failed %v\n", err)
		return
	}
	defer fileObj.Close() //关闭文件
	reader := bufio.NewReader(fileObj)
	for {
		line, err := reader.ReadString('\n')
		if err == io.EOF {
			fmt.Printf(line)
			return
		}
		if err != nil {
			fmt.Printf("readString file failed %v\n", err)
		}
		fmt.Printf(line)
	}

}

//ioutil
func readByIoutil() {

	content, err := ioutil.ReadFile("./xx.txt")
	if err != nil {
		fmt.Printf("read file by ioutil  failed,err %v \n", err)
	}
	fmt.Println(string(content))
}

//写入文件
func write() {
	fileObj, err := os.OpenFile("./xx2.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Printf("open file failed,err :%v\n", err)
		return
	}
	defer fileObj.Close()
	str := "沙河小王子"
	fileObj.Write([]byte(str)) //[]byte
	fileObj.WriteString("hello world")
}

func writeByBufio() {
	fileObj, err := os.OpenFile("./xx2.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Printf("open file failed,err :%v\n", err)
		return
	}
	defer fileObj.Close()
	writer := bufio.NewWriter(fileObj)
	writer.WriteString("贵州首席dps")
	writer.Flush()
}
func writeByIoutil() {
	srt := "我们由我不由天"
	err := ioutil.WriteFile("xx.txt", []byte(srt), 0644)
	if err != nil {
		fmt.Printf("write by iputil failed,err :%v\n",err)
		return
	}

}
// 复制文件
func cpFile()  {
	//1、读取文件
	content, err := ioutil.ReadFile("./xx.txt")
	if err != nil {
		fmt.Printf("read file by ioutil  failed,err %v \n", err)
	}
	//2、将文件内容写入新的文件如果没有就创建
	fileObj, err := os.OpenFile("./xx2.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
	if err != nil {
		fmt.Printf("open file failed,err :%v\n", err)
		return
	}
	defer fileObj.Close()
	writer := bufio.NewWriter(fileObj)
	//将文件写入缓存区
	writer.WriteString(string(content))
	//写入文件
	writer.Flush()

}
func main() {
	//readAll()
	//readByBufio()
	//readByIoutil()
	//write()
	//writeByBufio()
	//writeByIoutil()
	//cpFile()
}

循环
请先登录后发表评论
  • latest comments
  • 总共0条评论