golang:常用文件读写操作
文件读取:
package main import ( "bufio" "fmt" "io" "io/ioutil" "os" ) func ReadByOs() { //os库 f, err := os.Open("./in.txt") //os.Open():以只读方式打开文件 if err != nil { fmt.Printf("os.Open() failed, err:%v. ", err) } defer f.Close() buf := make([]byte, 1024) for { //循环读取文件数据 _, err := f.Read(buf) if err == io.EOF { break } if err != nil { fmt.Printf("f.Read() failed, err:%v. ", err) } fmt.Print(string(buf)) } } func ReadByBufio() { //bufio库,在os库file的基础上封装了一层API f, err := os.Open("./in.txt") //os.Open():以只读方式打开文件 if err != nil { fmt.Printf("os.Open() failed, err:%v. ", err) } defer f.Close() reader := bufio.NewReader(f) for { line, err := reader.ReadString('\\n') //一直读到分隔符,如果没有分隔符则err if err == io.EOF { break } if err != nil { fmt.Printf("reader.ReadString() failed, err:%v. ", err) } fmt.Print(line) } } func ReadByIoutil() { //ioutil库 bytes, err := ioutil.ReadFile("in.txt") //读取文件所有数据 if err != nil { fmt.Printf("ioutil.ReadFile() failed, err:%v. ", err) } fmt.Print(string(bytes)) } func ReadByIoutilAll(filename string) { f, err := os.Open(filename) defer f.Close() if err != nil { fmt.Println("os Open error: ", err) return } ioutil.ReadAll(f) } func main() { // ReadByOs() // ReadByBufio() ReadByIoutil() }
文件写入:
package main import ( "bufio" "fmt" "io/ioutil" "os" ) func writeByOs() { f, err := os.OpenFile("./out.txt", os.O_CREATE|os.O_RDWR, 0644) if err != nil { fmt.Printf("os.OpenFile() failed, err:%v. ", err) } defer f.Close() f.Write([]byte("测试输出1\\n")) f.WriteString("测试输出2\\n") } func writeByBufio() { f, err := os.OpenFile("./out.txt", os.O_CREATE|os.O_RDWR, 0644) if err != nil { fmt.Printf("os.OpenFile() failed, err:%v. ", err) } defer f.Close() writer := bufio.NewWriter(f) writer.Write([]byte("测试输出1\\n")) writer.WriteString("测试输出2\\n") writer.Flush() //需要清空缓冲区 } func writeByIoutil() { err := ioutil.WriteFile("./out.txt", []byte("测试输出1\\n测试输出2\\n"), 0666) if err != nil { fmt.Printf("ioutil.WriteFile() failed, err:%v. ", err) } } func main() { // writeByOs() // writeByBufio() writeByIoutil() }