4种读文件方式
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
func read0(path string) string {
f, err := ioutil.ReadFile(path)
if err != nil {
fmt.Printf("%s\n", err)
panic(err)
}
return string(f)
}
func read1(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
}
func read2(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
r := bufio.NewReader(fi)
chunks := make([]byte, 1024, 1024)
buf := make([]byte, 1024)
for {
n, err := r.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if 0 == n {
break
}
chunks = append(chunks, buf[:n]...)
}
return string(chunks)
}
func read3(path string) string {
fi, err := os.Open(path)
if err != nil {
panic(err)
}
defer fi.Close()
fd, err := ioutil.ReadAll(fi)
return string(fd)
}
func main() {
file := "/Applications/XAMPP/www/golang/web/src/test.log"
start := time.Now()
read1(file)
t0 := time.Now()
fmt.Printf("Cost time %v %s\n", t0.Sub(start), "os读")
read2(file)
t1 := time.Now()
fmt.Printf("Cost time %v %s\n", t1.Sub(t0), "带缓冲io读")
read0(file)
t2 := time.Now()
fmt.Printf("Cost time %v %s\n", t2.Sub(t1), "io读")
read3(file)
t3 := time.Now()
fmt.Printf("Cost time %v %s\n", t3.Sub(t2), "os-io读")
}
文件的字节大小决定哪种方法选用,os方式效率最慢,按照时间复杂度 os-io执行最快,当一个无限读取文件并持续运算时或者大的文件,有缓冲读取是最好的
有疑问加站长微信联系(非本文作者)