Go 文件操作(创建、打开、读、写)

1、使用io/ioutil进行文件操作:
a、读文件:

func ReadAll(r io.Reader) ([]byte, error)
func ReadFile(filename string) ([]byte, error)

b、写文件:


func WriteFile(filename string, data []byte, perm os.FileMode) error

2、使用os进行文件操作:
a、创建文件:

func Create(name string) (file *File, err error)
func NewFile(fd uintptr, name string) *File

b、打开文件:

func Open(name string) (*File, error)
func OpenFile(name string, flag int, perm FileMode) (*File, error)

c、读文件:

func (f *File) Read(b []byte) (n int, err error)

d、写文件:

func (f *File) Write(b []byte) (n int, err error)

3、使用bufio进行文件操作:
a、读文件:

func NewReader(rd io.Reader) *Reader
func (b *Reader) Read(p []byte) (n int, err error)
func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)

b、写文件:

func NewWriter(w io.Writer) *Writer
func (b *Writer) Write(p []byte) (nn int, err error)

4、代码示例:

package main

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

//read1()——read4() 读取速度依次变慢
func read1(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 read2(path string) string {
    fi, err := ioutil.ReadFile(path)
    if err != nil {
        panic(err)
    }

    return string(fi)
}

func read3(path string) string {
    fi, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer fi.Close()

    f := bufio.NewReader(fi)
    buf := make([]byte, 1024)
    chunks := make([]byte, 1024, 1024)

    for {
        n, err := f.Read(buf)
        if err != nil && err != io.EOF {
            panic(err)
        }
        if 0 == n {
            break
        }
        chunks = append(chunks, buf[:n]...)
    }

    return string(chunks)
}

func read4(path string) string {
    fi, err := os.Open(path)
    if err != nil {
        panic(err)
    }
    defer fi.Close()

    buf := make([]byte, 1024)
    chunks := make([]byte, 1024, 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 main() {
    file := "test.log"
    start := time.Now()

    read1(file)
    t1 := time.Now()
    fmt.Printf("Cost time %v\n", t1.Sub(start).Nanoseconds())

    read2(file)
    t2 := time.Now()
    fmt.Printf("Cost time %v\n", t2.Sub(t1).Nanoseconds())

    read3(file)
    t3 := time.Now()
    fmt.Printf("Cost time %v\n", t3.Sub(t2).Nanoseconds())

    read4(file)
    t4 := time.Now()
    fmt.Printf("Cost time %v\n", t4.Sub(t3).Nanoseconds())
}

总结:
read1()到read4()方法对文件的读取操作速率逐渐减小。

猜你喜欢

转载自blog.csdn.net/tovids/article/details/77887946
今日推荐