//利用bufio读取文件 funcreadFromByBufferIO(){ file, e := os.Open("./main.go") if e != nil { fmt.Println("文件读取失败") return } //记得关闭文件 defer file.Close() //创建一个用来读取文件内容的对象 reader := bufio.NewReader(file) for { s, e := reader.ReadString('\n') if e == io.EOF { fmt.Println("文件读取完毕") return } if e != nil { fmt.Println("文件读取失败") } fmt.Print(s) } }
ioutil读取整个文件
1 2 3 4 5 6 7 8 9
//利用IOUtil读取整个文件 funcreadFromByIOUtil(){ bytes, e := ioutil.ReadFile("./main.go") if e != nil { fmt.Println("文件读取失败") return } fmt.Println(string(bytes)) }
文件写入操作
os.OpenFile()能以指定模式打开文件,从而实现文件写入相关功能。
1 2 3
funcOpenFile(name string, flag int, perm FileMode)(*File ,error){ ... }
其中:
name:要打开文件的名字 ,flag打开文件的模式,perm文件权限。
模式
含义
os.O_WRONLY
只写
os.O_CREATE
创建文件
os.O_RDONLY
只读
os.O_RDWR
读写
os.O_TRUNC
清空
os.O_APPEND
追加
file写文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
//普通方式写入文件 funcwriteByFile(){ file, e := os.OpenFile("./a.txt", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) defer file.Close() if e != nil { fmt.Println("文件创建失败") return } //通过byte切片写入文件 file.Write([]byte("通过[]byte方式写文件\n")) //使用string方式写入文件 file.WriteString("通过string方式写入文件\n") if e != nil { fmt.Println("文件写入失败") return } }
bufio写文加
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//使用bufio写文件 funcwriteBybufIO(){ file, e := os.OpenFile("./b.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) defer file.Close() if e != nil { fmt.Println("文件创建失败") return } writer := bufio.NewWriter(file) //将数据写入缓存 writer.WriteString("通过string写文件") //将缓存中的数据写入文件 writer.Flush() }
ioutil写文件
1 2 3 4 5 6 7 8
//通过ioutil直接写文件 funcwriteByIOUtil(){ var str string = "通过ioutil直接向文件内写文件" err := ioutil.WriteFile("./c.txt", []byte(str), 0644) if err != nil { fmt.Println("文件写如失败") } }