美文网首页
Golang 读取文件的几种方式

Golang 读取文件的几种方式

作者: _Van丶 | 来源:发表于2020-08-07 10:41 被阅读0次

    一、一次性读取全部文件

    1、使用 os 包配合 ioutil 包读取

    package main
    
    import (
        "fmt"
        "io/ioutil"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            panic(err.Error())
        }
        defer file.Close()
        bytes, err := ioutil.ReadAll(file)
        if err != nil {
            panic(err.Error())
        }
        fmt.Println(string(bytes))
    }
    

    2、仅使用 ioutil 包读取

    package main
    
    import (
        "fmt"
        "io/ioutil"
    )
    
    func main() {
        bytes, err := ioutil.ReadFile("/yourPath/test.txt")
        if err != nil {
            panic(err.Error())
        }
        fmt.Println(string(bytes))
    }
    

    二、逐行读取文件

    1、使用 bufio.NewReader 方法

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        i := 0
        for {
            line, _, err := reader.ReadLine()
            if err == io.EOF {
                break
            }
            i++
            fmt.Printf("line%d: %s \n", i, string(line))
        }
    }
    

    2、使用 bufio.NewScanner 方法

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        scanner := bufio.NewScanner(file)
        i := 0
        for scanner.Scan() {
            line := scanner.Text()
            i++
            fmt.Printf("line%d: %s \n", i, string(line))
        }
    }
    

    三、按字节读取文件

    1、使用 file.Read 每次读取固定字节

    package main
    
    import (
        "fmt"
        "io"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        buf := make([]byte, 1024)
        bytes := make([]byte, 0)
        for {
            // 如果存在中文此方式可能出现乱码
            size, err := file.Read(buf)
            if err == io.EOF || size == 0 {
                break
            }
            bytes = append(bytes, buf[:size]...)
            // 加入分隔符验证
            // bytes = append(bytes, []byte("###")...)
        }
        fmt.Println(string(bytes))
    }
    

    2、使用 bufio.Read 每次读取固定字节

    package main
    
    import (
        "bufio"
        "fmt"
        "io"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        buf := make([]byte, 50)
        bytes := make([]byte, 0)
        for {
            // 如果存在中文此方式可能出现乱码
            size, err := reader.Read(buf)
            if err == io.EOF || size == 0 {
                break
            }
            bytes = append(bytes, buf[:size]...)
            // 加入分隔符验证
            // bytes = append(bytes, []byte("###")...)
        }
        fmt.Println(string(bytes))
    }
    

    3、使用 bufio.ReadByte 每次读取一个字节

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/Users/van/WorkSpace/go/learngo/fileOperation/file/ID2Path_size.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        bytes := make([]byte, 0)
        for {
            byte, err := reader.ReadByte()
            if err != nil {
                break
            }
            bytes = append(bytes, byte)
            // fmt.Printf("%s \n", string(byte))
        }
        fmt.Printf("content: %s \n", string(bytes))
    }
    

    4、使用 bufio.ReadRune 每次读取一个字符

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        runes := make([]rune, 0)
        for {
            readRune, size, err := reader.ReadRune()
            if err != nil || size == 0 {
                break
            }
            runes = append(runes, readRune)
            // fmt.Printf("%d - %s \n", size, string(readRune))
        }
        fmt.Printf("content: %s \n", string(runes))
    }
    

    四、按分隔符读取文件

    1、 bufio.ReadBytes

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        bytes := make([]byte, 0)
        for {
            bytesTmp, err := reader.ReadBytes('\n')
            if err != nil {
                break
            }
            bytes = append(bytes, bytesTmp...)
            // fmt.Printf("%s \n", string(bytesTmp))
        }
        fmt.Printf("content: %s \n", string(bytes))
    }
    

    2、bufio.ReadSlice

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        bytes := make([]byte, 0)
        for {
            line, err := reader.ReadSlice('\n')
            if err != nil {
                break
            }
            bytes = append(bytes, line...)
            // fmt.Printf("%s \n", string(line))
        }
        fmt.Printf("content: %s \n", string(bytes))
    }
    

    3、bufio.ReadString

    package main
    
    import (
        "bufio"
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Open("/yourPath/test.txt")
        if err != nil {
            log.Fatalf("open file failed: %s \n", err.Error())
        }
        defer file.Close()
        reader := bufio.NewReader(file)
        var content string
        for {
            str, err := reader.ReadString('\n')
            if err != nil {
                break
            }
            content += str
            // fmt.Printf("%s \n", str)
        }
        fmt.Printf("content: %s \n", content)
    }
    

    以上,Van(完)。

    相关文章

      网友评论

          本文标题:Golang 读取文件的几种方式

          本文链接:https://www.haomeiwen.com/subject/tdffdktx.html