Go文件操作

读取文件中的内容

假设你想获取文件中感兴趣的内容,但是,你不希望获取所有内容。假设文件的内容如下所示:

Go文件操作_第1张图片

1. 网页视觉设计理论之少些质感,多些版式.
http://www.ynetx.com/theory/560-1.html

2. 设计理论:
http://www.ynetx.com/design/theory/

3.Google的新设计理念Material Design
http://www.infoq.com/cn/news/2014/07/google-material-design-android/

你只想获取http开头的行内容。实现代码如下:

line, err := reader.ReadString('\n')

        // skip all line starting without line 'http'
        // if equal := strings.Index(line, "http"); equal < 0 {
        // fmt.Print(line)
        // }

        //alternatively, only print line starting with 'http'
        if equal := strings.Index(line, "http"); equal >= 0 {
            fmt.Print(line)
        }

完整代码如下所示:

package main
import (
    "bufio"
    "bytes"
    "fmt"
    "io"
    "os"
    "strings"
    "unicode"
)


func ReadFile(filePath string) {
    file, err := os.Open(filePath)

    if err != nil {
        fmt.Println(err)
        return
    }

    defer file.Close()

    reader := bufio.NewReader(file)

    for {
        line, err := reader.ReadString('\n')

        // skip all line starting without line 'http'
        // if equal := strings.Index(line, "http"); equal < 0 {
        // fmt.Print(line)
        // }

        //alternatively, only print line starting with 'http'
        if equal := strings.Index(line, "http"); equal >= 0 {
            fmt.Print(line)
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            fmt.Println(err)
        }

    }

}

func main(){
    //文件路径../util/art.txt
    ReadFile("../util/art.txt")
}

输出结果:

http://www.ynetx.com/theory/560-1.html
http://www.ynetx.com/design/theory/
http://www.infoq.com/cn/news/2014/07/google-material-design-android/

欢迎加入我的微信公众号

你可能感兴趣的:(Go)