美文网首页
GO语言最简单的读写文件demo

GO语言最简单的读写文件demo

作者: 佛心看世界 | 来源:发表于2019-04-26 14:52 被阅读0次

读文件


package main

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

func main() {
    //使用os.Open 打开一个文件,   记得这个文件要存在.
    inputFile, inputError := os.Open("input.dat")
    if inputError != nil {
        fmt.Printf("An error occurred on opening the inputfile\n" +
            "Does the file exist?\n" +
            "Have you got acces to it?\n")
        return // exit the function on error
    }
    //用defer 关闭文件
    defer inputFile.Close()
    //用bufio.NewReader 创建reader接口
    inputReader := bufio.NewReader(inputFile)
    for {
        //用readstrings 读取每行数据
        inputString, readerError := inputReader.ReadString('\n')
        // inputString 是[]byte{}类型
        fmt.Printf("The input was: %s", inputString)
        // 用  readerError = io.EOF 判断读取是否结束
        if readerError == io.EOF {
            return
        }
    }
}


将整个文件的内容读到一个字符串里


package main

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

func main() {
    inputFile := "products.txt"
    outputFile := "products_copy.txt"
    // 使用ioutil.ReadFile 可以把文件直接全部读取出来.  buf 是 []byte 类型
    buf, err := ioutil.ReadFile(inputFile)
    if err != nil {
        fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
        // panic(err.Error())
    }
    fmt.Printf("%s\n", string(buf))
    // 使用 ioutil.WriteFile  写入某个文件中
    err = ioutil.WriteFile(outputFile, buf, 0644) // oct, not hex
    if err != nil {
        panic(err.Error())
    }
}


按列读取文件中的数据

package main

import (
    "fmt"
    "os"
)

func main() {
    // os.Open  打开文件
    file, err := os.Open("products2.txt")
    if err != nil {
        panic(err)
    }
    //记得要关闭
    defer file.Close()


    //创建三列的数据
    var col1, col2, col3 []string
    for {
        var v1, v2, v3 string
        // fmt.Fscanln 来读取每列的数据  记住这个只能以空格为分隔符   每次读一行
        _, err := fmt.Fscanln(file, &v1, &v2, &v3)
        if err != nil {
            break
        }
        //放入相应数据
        col1 = append(col1, v1)
        col2 = append(col2, v2)
        col3 = append(col3, v3)
    }

    fmt.Println(col1)
    fmt.Println(col2)
    fmt.Println(col3)
}


写文件

package main

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

func main () {
    // 使用  os.OpenFile  来打开创建某个文件,如果此文件不存在,则自动创建
    outputFile, outputError := os.OpenFile("output.dat", os.O_WRONLY|os.O_CREATE, 0666)
    if outputError != nil {
        fmt.Printf("An error occurred with file opening or creation\n")
        return  
    }
    //记住要关闭哦
    defer outputFile.Close()

    // 创建 writer 用bufio库
    outputWriter := bufio.NewWriter(outputFile)
    outputString := "hello world!\n"

    for i:=0; i<10; i++ {
        outputWriter.WriteString(outputString)
    }
    //记得要刷新,写入文件
    outputWriter.Flush()
}

package main

import "os"

func main() {
    //简单粗暴型
    f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0666)
    defer f.Close()
    //直接写入
    f.WriteString("hello, world in a file\n")
}

文件拷贝

// filecopy.go
package main

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

func main() {
    CopyFile("target.txt", "source.txt")
    fmt.Println("Copy done!")
}

func CopyFile(dstName, srcName string) (written int64, err error) {
    //判断是否能打开
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()
    //判断是否能创建
    dst, err := os.Create(dstName)
    if err != nil {
        return
    }
    defer dst.Close()
    //使用 io Copy  来完成拷贝
    return io.Copy(dst, src)
}

相关文章

网友评论

      本文标题:GO语言最简单的读写文件demo

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