美文网首页
Go语言学习四:I/O

Go语言学习四:I/O

作者: 孙小兵 | 来源:发表于2018-01-13 18:52 被阅读0次

    Go 语言I/O 涉及两大部分 :I/O ,File

    一  I/O 

    /**

    bufio包实现了有缓冲的I/O。它包装一个io.Reader或io.Writer接口对象,

    创建另一个也实现了该接口,且同时还提供了缓冲和一些文本I/O的帮助函数的对象。

    */

    functestBufio()  {

    //r:=strings.NewReader("hello,world")

    //rd:=bufio.NewReader(r)

    //

    //p:=make([]byte,30)

    //rd.Read(p)

    //fmt.Println(string(p))

    w:=bufio.NewWriter(bytes.NewBuffer(make([]byte,0)))

    w.WriteString(" nihao")

    w.Flush()

    fmt.Println(w.Buffered())

    }

    /**

    bytes 包 下的 reader  、 buffer

    buffer实现了 bufio包中 reader 、writer 接口

    */

    functestBytes()  {

    r:=bytes.NewReader([]byte("hello"))

    b:=make([]byte,2)

    r.Read(b)

    fmt.Println(r.Size())

    fmt.Println(r.Len())

    buffer:=bytes.NewBufferString("hello,world")

    fmt.Println(buffer.Len())

    buffer.WriteString(" sunhongtao")

    fmt.Println(buffer.String())

    }

    /**

    io包提供了对I/O原语的基本接口。本包的基本任务是包装这些原语已有的实现(如os包里的原语),

    使之成为共享的公共接口,这些公共接口抽象出了泛用的函数并附加了一些相关的原语的操作。

    因为这些接口和原语是对底层实现完全不同的低水平操作的包装,

    除非得到其它方面的通知,客户端不应假设它们是并发执行安全的。

    */

    functestIO()  {

    w:=bufio.NewWriter(bytes.NewBufferString("hello"))

    io.WriteString(w,"world")

    w.Flush()

    b,_:=ioutil.ReadAll(bytes.NewBufferString("nihao"))

    fmt.Println(string(b))

    s,_:=ioutil.ReadFile("E:\\hello.txt")

    fmt.Println(string(s))

    ioutil.WriteFile("E:\\hello.txt",[]byte("welcome"),7777)

    }

    二 File 

    funccreateFile() {

    file,e := os.Create("E://hello.txt")

    ife != nil {

    panic(e)

    }

    deferfile.Close()

    file.WriteString("hello,world")

    fmt.Println(file.Name())

    }

    funcreadFile() {

    file,err := os.Open("e://hello.txt")

    iferr != nil {

    panic(err)

    }

    deferfile.Close()

    //方案一

    //by,_:=ioutil.ReadAll(file)

    //fmt.Println(string(by))

    //方案二

    buffer := bytes.NewBufferString("")

    varb =make([]byte,100)

    for{

    n,e := file.Read(b)

    fmt.Println(n)

    ife != nil && e != io.EOF {

    panic(e)

    }

    ifn >0&& n <=len(b) {

    buffer.Write(b[:n])

    }else{

    break

    }

    }

    fmt.Println(buffer.String())

    }

    funcwriteFile() {

    file,err := os.Open("e://hello.txt")

    iferr != nil {

    panic(err)

    }

    deferfile.Close()

    file.WriteString("nihao")

    }

    相关文章

      网友评论

          本文标题:Go语言学习四:I/O

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