Go语言文件读取

幸运草 2020年4月18日22:56:50前端框架评论阅读模式

Go语言文件读取

文件读取

读取文件内容如下:

cat ./file.txt 
最近很火的一首小诗:

纽约时间比加州时间早三个小时,

New York is 3 hours ahead of California,

但加州时间并没有变慢。

but it does not make California slow.

有人22岁就毕业了,

Someone graduated at the age of 22,

但等了五年才找到好的工作!

but waited 5 years before securing a good job!

有人25岁就当上CEO,

Someone became a CEO at 25,

却在50岁去世。

and died at 50.

也有人迟到50岁才当上CEO,

While another became a CEO at 50,

然后活到90岁。

and lived to 90 years.

有人依然单身,

Someone is still single,

同时也有人已婚。

while someone else got married.

奥巴马55岁就退休,

Obama retires at 55,

川普70岁才开始当总统。

but Trump starts at 70.

世上每个人本来就有自己的发展时区。

Absolutely everyone in this world works based on their Time Zone.

身边有些人看似走在你前面,

People around you might seem to go ahead of you,

也有人看似走在你后面。

some might seem to be behind you.

但其实每个人在自己的时区有自己的步程。

But everyone is running their own RACE, in their own TIME.

不用嫉妒或嘲笑他们。

Don’t envy them or mock them.

他们都在自己的时区里,你也是!

They are in their TIME ZONE, and you are in yours!

生命就是等待正确的行动时机。

Life is about waiting for the right moment to act.

所以,放轻松。

So, RELAX.

你没有落后。

You’re not LATE.

你没有领先。

You’re not EARLY.

在命运为你安排的属于自己的时区里,一切都准时。

You are very much ON TIME, and in your TIME ZONE Destiny set up for you.

使用 os包按byte读取文件常用方法:

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

Read方法从f中读取最多len(b)字节数据并写入b。它返回读取的字节数和可能遇到的任何错误。文件终止标志是读取0个字节且返回值err为io.EOF。

func (f *File) ReadAt(b []byte, off int64) (n int, err error)

ReadAt从指定的位置(相对于文件开始位置)读取len(b)字节数据并写入b。它返回读取的字节数和可能遇到的任何错误。当n<len(b)时,本方法总是会返回错误;如果是因为到达文件结尾,返回值err会是io.EOF。

代码实现:

package main

import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("./file.txt")
    if err != nil {
        fmt.Printf("open ./file.txt err : %vn", err)
    }
    if file != nil {
        defer func(file *os.File) { file.Close() }(file)
    }

    var b1 = make([]byte, 102)
    space1, err := file.Read(b1)
    if err != nil {
        fmt.Printf("file read err : %vn", err)
    }
    fmt.Printf("file read success , 读取 %d 字节。n", space1)
    fmt.Printf("读取内容:n%sn", string(b1))

    b2 := make([]byte, 205)
    space2, err := file.ReadAt(b2, int64(space1))
    if err != nil {
        fmt.Printf("file readat err : %vn", err)
    }
    fmt.Printf("file readat success , 读取 %d 字节。n", space2)
    fmt.Printf("读取内容:n%sn", string(b2))
}

缓冲读取

bufio包实现了有缓冲的I/O。它包装一个io.Reader或io.Writer接口对象,创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象。

缓冲读取常用函数和方法:

func NewReader(rd io.Reader) *Reader

NewReader创建一个具有默认大小缓冲、从r读取的*Reader。

func (b *Reader) Read(p []byte) (n int, err error)

Read读取数据写入p。本方法返回写入p的字节数。本方法一次调用最多会调用下层Reader接口一次Read方法,因此返回值n可能小于len(p)。读取到达结尾时,返回值n将为0而err将为io.EOF。

func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)

ReadLine是一个低水平的行数据读取原语。大多数调用者应使用ReadBytes('n')或ReadString('n')代替,或者使用Scanner。

ReadLine尝试返回一行数据,不包括行尾标志的字节。如果行太长超过了缓冲,返回值isPrefix会被设为true,并返回行的前面一部分。该行剩下的部分将在之后的调用中返回。返回值isPrefix会在返回该行最后一个片段时才设为false。返回切片是缓冲的子切片,只在下一次读取操作之前有效。ReadLine要么返回一个非nil的line,要么返回一个非nil的err,两个返回值至少一个非nil。

返回的文本不包含行尾的标志字节("rn"或"n")。如果输入流结束时没有行尾标志字节,方法不会出错,也不会指出这一情况。在调用ReadLine之后调用UnreadByte会总是吐出最后一个读取的字节(很可能是该行的行尾标志字节),即使该字节不是ReadLine返回值的一部分。

func (b *Reader) ReadSlice(delim byte) (line []byte, err error)

ReadSlice读取直到第一次遇到delim字节,返回缓冲里的包含已读取的数据和delim字节的切片。该返回值只在下一次读取操作之前合法。如果ReadSlice放在在读取到delim之前遇到了错误,它会返回在错误之前读取的数据在缓冲中的切片以及该错误(一般是io.EOF)。如果在读取到delim之前缓冲就被写满了,ReadSlice失败并返回ErrBufferFull。因为ReadSlice的返回值会被下一次I/O操作重写,调用者应尽量使用ReadBytes或ReadString替代本法功法。当且仅当ReadBytes方法返回的切片不以delim结尾时,会返回一个非nil的错误。

func (b *Reader) ReadBytes(delim byte) (line []byte, err error)

ReadBytes读取直到第一次遇到delim字节,返回一个包含已读取的数据和delim字节的切片。如果ReadBytes方法在读取到delim之前遇到了错误,它会返回在错误之前读取的数据以及该错误(一般是io.EOF)。当且仅当ReadBytes方法返回的切片不以delim结尾时,会返回一个非nil的错误。

func (b *Reader) ReadString(delim byte) (line string, err error)

ReadString读取直到第一次遇到delim字节,返回一个包含已读取的数据和delim字节的字符串。如果ReadString方法在读取到delim之前遇到了错误,它会返回在错误之前读取的数据以及该错误(一般是io.EOF)。当且仅当ReadString方法返回的切片不以delim结尾时,会返回一个非nil的错误。

代码实现:

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

func main() {
    file, err := os.Open("./file.txt")
    if err != nil {
        fmt.Printf("os open ./file.txt err : %vn", err)
    }
    if file != nil {
        defer func(file *os.File) { file.Close() }(file)
    }

    read1 := bufio.NewReader(file)

    var b1 = make([]byte, 102)
    readByte1, err := read1.Read(b1)
    if err != nil {
        fmt.Printf("read err : %vn", err)
    }
    fmt.Printf("read success , 读取 %d 字节n读取的内容:n%sn", readByte1, string(b1))

    var line []byte
    for {
        data, prefix, err := read1.ReadLine()
        if err == io.EOF {
            // fmt.Println(err)
            break
        }

        line = append(line, data...)
        if !prefix {
            // fmt.Printf("data:%sn", string(line))
        }
    }
    fmt.Println(string(line))
}

读取整个文件

使用 io/ioutil 包实现了读取整个文件功能

读取整个文件常用函数:

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

ReadAll从r读取数据直到EOF或遇到error,返回读取的数据和遇到的错误。成功的调用返回的err为nil而非EOF。因为本函数定义为读取r直到EOF,它不会将读取返回的EOF视为应报告的错误。

func ReadFile(filename string) ([]byte, error)

ReadFile 从filename指定的文件中读取数据并返回文件的内容。成功的调用返回的err为nil而非EOF。因为本函数定义为读取整个文件,它不会将读取返回的EOF视为应报告的错误。

代码实现:

package main

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

func main() {
    file, err := os.Open("./file.txt")
    if err != nil {
        fmt.Printf("open ./file.txt err : %vn", err)
    }
    if file != nil {
        defer func(file *os.File) { file.Close() }(file)
    }

    data1, err := ioutil.ReadAll(file)
    if err != nil {
        fmt.Printf("ioutil read all err : %vn", err)
    }
    fmt.Printf("ioutil read all success.n内容:n%sn", string(data1))

    data2, err := ioutil.ReadFile("./file.txt")
    if err != nil {
        fmt.Printf("ioutil read file err : %vn", err)
    }
    fmt.Printf("ioutil read file success.n内容:n%sn", string(data2))
}

特别声明:以上文章内容仅代表作者本人观点,不代表变化吧观点或立场。如有关于作品内容、版权或其它问题请于作品发表后的30日内与变化吧联系。

  • 赞助本站
  • 微信扫一扫
  • weinxin
  • 加入Q群
  • QQ扫一扫
  • weinxin
幸运草
Go语言接口规则 前端框架

Go语言接口规则

Go语言接口规则 接口是一个或多个方法签名的集合。任何类型的方法集中只要拥有该接口对应的全部方法签名。就表示它 "实现" 了该接口,无须在该类型上显式声明实现了哪个接口。对应方法,是指有相同名称、参数...
Go语言中处理 HTTP 服务器 前端框架

Go语言中处理 HTTP 服务器

1 概述 包 net/http 提供了HTTP服务器端和客户端的实现。本文说明关于服务器端的部分。 快速开始: package main import (   "log"   "net/http" )...

发表评论