Go基础---->go的基础学习(五)

  这里是go中关于io的一些知识。有时不是你装得天衣无缝,而是我愿意陪你演得完美无缺。

 go中关于io的使用

一、Reader中的Read方法

Read 用数据填充指定的字节 slice,并且返回填充的字节数和错误信息。 在遇到数据流结尾时,返回 io.EOF 错误。

package main

import (
    "fmt"
    "io"
    "strings"
)

func main() {
    r := strings.NewReader("Hello, My name is huhx!")
    b := make([]byte, 16)
    for {
        n, err := r.Read(b)
        fmt.Printf("n = %v err = %v b = %v
", n, err, b)
        fmt.Printf("b[:n] = %q
", b[:n])
        if err == io.EOF {
            break
        }
    }
}

 运行的结果如下:

n = 16 err = <nil> b = [72 101 108 108 111 44 32 77 121 32 110 97 109 101 32 105]
b[:n] = "Hello, My name i"
n = 7 err = <nil> b = [115 32 104 117 104 120 33 77 121 32 110 97 109 101 32 105]
b[:n] = "s huhx!"
n = 0 err = EOF b = [115 32 104 117 104 120 33 77 121 32 110 97 109 101 32 105]
b[:n] = ""

二、go中的写入文件

package main 

import (
    "fmt"
    "os"
)

func main() {
    userFile := "huhx.txt"
    fout, err := os.Create(userFile)
    defer fout.Close()
    if err != nil {
        fmt.Println(userFile, err)
        return
    }
    for i := 0; i < 10; i++ {
        fout.WriteString("I love you, huhx.
")
        fout.Write([]byte("My name is huhx!
"))
    }
}

生成的目录结构:

 三、go中的读取文件

package main 

import (
    "fmt"
    "os"
)

func main() {
    userFile := "huhx.txt"
    fl, err := os.Open(userFile)
    defer fl.Close()
    if err != nil {
        fmt.Println(userFile, err)
        return
    }
    buf := make([]byte, 1024)
    for {
        n, _ := fl.Read(buf)
        if 0 == n {
            break
        }
        os.Stdout.Write(buf[:n])
    }
}

 运行的结果如下:

I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!
I love you, huhx.
My name is huhx!

 四、go中删除文件

package main 

import (
    "fmt"
    "os"
)

func main() {
    err := os.Remove("huhx.txt")
    if err != nil {
        fmt.Println("file remove Error!")
        fmt.Printf("%s", err)
    } else {
        fmt.Println("file remove OK!")
    }
}

第一次删除时:

file remove OK!

第二次删除时(文件已经成功删除):

file remove Error!
remove huhx.txt: The system cannot find the file specified.

五、目录的创建以及删除

package main

import (
    "fmt"
    "os"
)
func main() {
    os.Mkdir("astaxie", 0777)
    os.MkdirAll("astaxie/test1/test2", 0777)
    err := os.Remove("astaxie")
    if err != nil {
        fmt.Println(err) // remove astaxie: The directory is not empty.
    }
    os.RemoveAll("astaxie")
}
  • func Remove(name string) error

删除名称为name 的目录,当目录下有文件或者其他目录是会出错

  • func RemoveAll(path string) error

根据path删除多级子目录,如果 path是单个名称,那么该目录不删除。

友情链接

原文地址:https://www.cnblogs.com/huhx/p/baseusego5.html