Go实战--golang中读写文件的几种方式
生命不止,继续 go go go !!! 读写文件应该是在开发过程中经常遇到的,今天要跟大家一起分享的就是在golang的世界中,如何读写文件。 使用io/ioutil进行读写文件 先回忆下之前的ioutil包介绍: 其中提到了两个方法: func ReadFile(filename string) ([]byte,error)
ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil,not err == EOF. Because ReadFile reads the whole file,it does not treat an EOF from Read as an error to be reported. func WriteFile func WriteFile(filename string,data []byte,perm os.FileMode) error
WriteFile writes data to a file named by filename. If the file does not exist,WriteFile creates it with permissions perm; otherwise WriteFile truncates it before writing. 读文件: package main
import (
"fmt"
"io/ioutil"
)
func main() {
b,err := ioutil.ReadFile("test.log")
if err != nil {
fmt.Print(err)
}
fmt.Println(b)
str := string(b)
fmt.Println(str)
}
写文件: func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
d1 := []byte("hellongon")
err := ioutil.WriteFile("test.txt",d1, 0644)
check(err)
}
使用os进行读写文件 同样,先回忆下之前的os包的介绍: 首先要注意的就是两个打开文件的方法: func Open(name string) (*File,sans-serif; font-size:14px"> Open opens the named file for reading. If successful,methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error,it will be of type *PathError.
func OpenFile func OpenFile(name string,flag int,perm FileMode) (*File,sans-serif; font-size:14px"> OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm,(0666 etc.) if applicable. If successful,methods on the returned File can be used for I/O. If there is an error,21)">"log"
"os"
)
func main() {
f,err := os.OpenFile("notes.txt",os.O_RDWR|os.O_CREATE, 0755)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
读方法 "bufio"
"io"
"io/ioutil"
func main() {
f,err := os.Open("/tmp/dat")
check(err)
b1 := make([]byte, 5)
n1,err := f.Read(b1)
check(err)
fmt.Printf("%d bytes: %sn",n1,string(b1))
o2,err := f.Seek(6, 0)
check(err)
b2 := 2)
n2,err := f.Read(b2)
check(err)
fmt.Printf("%d bytes @ %d: %sn",n2,o2,string(b2))
o3, 0)
check(err)
b3 := 2)
n3,err := io.ReadAtLeast(f,b3, 2)
check(err)
fmt.Printf(string(b3))
_,err = f.Seek(0, 0)
check(err)
r4 := bufio.NewReader(f)
b4,err := r4.Peek(5)
check(err)
fmt.Printf("5 bytes: %sn",string(b4))
f.Close()
}
写方法 "/tmp/dat2")
check(err)
defer f.Close()
d2 := []byte{115, 111, 109, 101, 10}
n2,err := f.Write(d2)
check(err)
fmt.Printf("wrote %d bytesn",n2)
n3,err := f.WriteString("writesn")
fmt.Printf("bufferedn")
fmt.Printf( 几种读取文件方法速度比较
|