美文网首页
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

    Go 语言I/O 涉及两大部分 :I/O ,File 一 I/O /** bufio包实现了有缓冲的I/O。它包装...

  • Go入门系列(六)I/O

    目录:一、终端I/O二、文件I/O 一、终端I/O Go语言的终端I/O操作在基础包上有封装了多种,我们以fmt包...

  • Go netpoller

    摘要 这边文章将介绍 Go 如何处理网络 I/O 阻塞I/O 在Go中,所有的I/O都是阻塞的。 Go生态系统是围...

  • NIO-异步IO

    异步I/O Github Demo 连网是学习异步 I/O 的很好基础,而异步 I/O 对于在 Java 语言中执...

  • 2017年为什么要努力?这是我见过最好的回答

    I Believe I Can Fly I used to think that I could not go o...

  • 问问答答

    When do you go to school? I go to school, at, seven o'clo...

  • 06-输入输出函数-指趣学院

    Go语言fmt包实现了类似C语言printf和scanf的格式化I/O, 格式化动作源自C语言但更简单 输出函数 ...

  • One Funny Day

    On Sunday.I go to the supermarket with mother.I buy lot o...

  • 笨办法学golang(四)

    这是Go语言学习笔记的第四篇 Go语言学习笔记参考书籍「Go语言圣经」以及Go官方标准库 数组 数组是指一系列同类...

  • 作业

    今儿作业多(๑•́o•̀๑) ↯↯,but I am a Straight A studentm. I am go...

网友评论

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

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