第12章 读写数据

2020-01-19  本文已影响0人  yezide

1、 读取用户输入from console

package main

import "fmt"

var (
    firstName, lastName, s string
    i int
    f float32
    input = "56.12 / 5212 / Go"
    format = "%f / %d / %s"
)

func main() {
    // fmt.Println("Please enter your full name: ")
    // fmt.Scanln(&firstName, &lastName)
    // fmt.Printf("hi %s %s\n", firstName, lastName)

    // 这种方式是根据指定格式拆分字段?
    fmt.Sscanf(input, format, &f, &i, &s)
    fmt.Println("From the string we read: ", f, i, s)
}

2、用bufio读取用户输入

package main

import "fmt"
import "bufio"
import "os"

func main() {
    var inputReader *bufio.Reader
    var input string
    var err error

    inputReader = bufio.NewReader(os.Stdin)
    fmt.Println("Please enter some input: ")
    input, err = inputReader.ReadString('\n')
    if err == nil {
        fmt.Printf("The input was: %s\n", input)
    }
}

3、读取文件

package main

import "fmt"
import "bufio"
import "os"
import "io"
import "io/ioutil"

func main() {
    fileName := "/Users/lijingle/Downloads/aa.txt"
    inputFile, inputError := os.Open(fileName)
    if inputError != nil {
        fmt.Println("文件不存在!")
        return
    }

    // 无法如何文件一定要关闭
    defer inputFile.Close()

    inputReader := bufio.NewReader(inputFile)
    // 按行读取文件
    for {
        readLine, readError := inputReader.ReadString('\n')
        if readError != io.EOF {
            fmt.Printf("The input was: %s", readLine)
        } else {
            break
        }
    }

    // 读取整个文件到string中
    buf, err2 := ioutil.ReadFile(fileName)
    if err2 != nil {
        fmt.Printf("err2: %s", err2)
    }
    fmt.Printf("整个文件内容为:\n%s", string(buf))
}

3、读取压缩文件

package main

import "fmt"
import "bufio"
import "os"
import "io"
import "compress/gzip"

func main() {
    fileName := "/Users/lijingle/Downloads/aa.txt"
    inputFile, inputError := os.Open(fileName)
    if inputError != nil {
        fmt.Println("文件不存在!")
        return
    }

    // 无法如何文件一定要关闭
    defer inputFile.Close()

    fz, err := gzip.NewReader(inputFile)
    var reader *bufio.Reader
    if err != nil {
        //  不是压缩文件
        //  原书实际测试无法读出内容, 我怀疑是inputFile被gzip读掉了? 
        //  经验证确实是的, 要按照下面这重读inputFile
        inputFileNew, _ := os.Open(fileName)
        defer inputFileNew.Close()
        reader = bufio.NewReader(inputFileNew)
    } else {
        // 压缩文件
        reader = bufio.NewReader(fz)
    }
    for {
        line, err1 := reader.ReadString('\n')
        if err1 != io.EOF {
            fmt.Printf(line)
        } else {
            break
        }
    }
}

4、写文件

package main

import "fmt"
import "bufio"
import "os"
import "io"

func main() {
    fileName1 := "/Users/lijingle/Downloads/aa.txt"
    fileName2 := "/Users/lijingle/Downloads/write.txt"
    
    inputFile, _ := os.Open(fileName1)
    outputFile, _ := os.OpenFile(fileName2, os.O_WRONLY|os.O_CREATE, 0666)

    defer inputFile.Close()
    defer outputFile.Close()

    inputReader := bufio.NewReader(inputFile)
    outputWriter := bufio.NewWriter(outputFile)

    for {
        line, err := inputReader.ReadString('\n')
        fmt.Printf(line)
        outputWriter.WriteString(line)
        if err == io.EOF {
            break
        }
    }
    outputWriter.Flush()
}

5、接收命令参数

package main

import "fmt"
import "os"

func main() {
    // 入参是个切片,第0个是程序本身名字
    fmt.Printf("heddlo: %s\n", os.Args[1:])
    // 还有个flag包, 是用于接收 echo -n 这种参数的,用的时候再来看吧, 挺简单的
}

6、 大家来找错误

package main

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

func main() {
    inputFile, _ := os.Open("/Users/lijingle/Downloads/aa.txt")
    outputFile, _ := os.OpenFile("/Users/lijingle/Downloads/ww.txt", os.O_WRONLY|os.O_CREATE, 0666)
    defer inputFile.Close()
    defer outputFile.Close()
    inputReader := bufio.NewReader(inputFile)
    outputWriter := bufio.NewWriter(outputFile)
    for {
        inputString, _, readerError := inputReader.ReadLine()
        if readerError == io.EOF {
            fmt.Println("readerError EOF")
            // 错误在这里, 如果用return的话, 会defer掉它,  outputFile就close掉了,导致最后无法Flush
            break
        }
        outputString := string(inputString[2:5]) + "\n"
        fmt.Println(outputString)
        _, err := outputWriter.WriteString(outputString)
        if err != nil {
            return 
        }
    }
    outputWriter.Flush()
    fmt.Println("Conversion done")
}
上一篇下一篇

猜你喜欢

热点阅读