读写文件应该是在开发过程中经常遇到的,今天要跟大家一起分享的就是在golang的世界中,如何读写文件
读写文件应该是在开发过程中经常遇到的,今天简单看看golang的世界中,如何读写文件。
读取文件方法速度比较
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 := "test.log"
start := time.Now()
read0(file)
t0 := time.Now()
fmt.Printf("Cost time %v\n", t0.Sub(start))
read1(file)
t1 := time.Now()
fmt.Printf("Cost time %v\n", t1.Sub(t0))
read2(file)
t2 := time.Now()
fmt.Printf("Cost time %v\n", t2.Sub(t1))
read3(file)
t3 := time.Now()
fmt.Printf("Cost time %v\n", t3.Sub(t2))
}
运行结果对比:
Cost time 4.0105ms
Cost time 11.5043ms
Cost time 7.0042ms
Cost time 2.4983ms
Cost time 4.4925ms
Cost time 11.0053ms
Cost time 5.0082ms
Cost time 2.9992ms
Cost time 3.9866ms
Cost time 15.0085ms
Cost time 7.5054ms
Cost time 2.5035ms
Cost time 4.9989ms
Cost time 14.0112ms
Cost time 7.5045ms
Cost time 3.508ms
Cost time 3.0043ms
Cost time 15.0265ms
Cost time 8.9884ms
Cost time 2.0036ms
静态文件
//=================================== Files ===================================//
func File_Server() {
mux := http.NewServeMux()
mux.Handle("/", &fileHanlder{})
mux.HandleFunc("/hello", sayServer2)
wd, err := os.Getwd()
if err != nil {
panic(err)
}
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(wd))))
err = http.ListenAndServe(":8080", mux)
if err != nil {
panic(err)
}
}
type fileHanlder struct{}
func (*fileHanlder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
io.WriteString(w,"Http Service: "+ r.URL.String())
}
func sayServer2(w http.ResponseWriter, r *http.Request) {
io.WriteString(w,"sayServer2 Http Service")
}