Go内置库中io.Reader/Writer是比较常用的接口。很多原生的接口都围绕这个系列的接口展开,在实际的开发过程中,你会发现通过这个接口可以在多种不同的io类型之间进行过渡和转化。
围绕io.Reader/Writer,Go语言中有几个常用的实现:
-
net.Conn, os.Stdin, os.File: 网络、标准输入输出、文件的流读取
-
strings.Reader: 把字符串抽象成Reader
-
bytes.Reader: 把[]byte抽象成Reader
-
bytes.Buffer: 把[]byte抽象成Reader和Writer
-
bufio.Reader/Writer: 抽象成带缓冲的流读取(比如按行读写)
可以看到os.File结构也实现了Reader和Writer接口。Go语言内置的文件读写函数有很多都是基于Reader和Writer接口实现的。
Go语言中文件读写主要涉及到4个包:
-
os
-
io
-
bufio
-
ioutil
os和io包读写文件和目录
Go语言最基础的打开文件函数os.OpenFile:
file2, error := os.OpenFile("./2.txt", os.O_RDWR|os.O_CREATE, 0766) // 返回File指针,打开的文件将会拥有O_RDWR权限(读写权限),传入的os.O_CREATE的意思是,如果文件不存在,则创建该文件,如果创建了文件,则该文件的权限设置为0766
if error != nil {
fmt.Println(error);
}
fmt.Println(file2);
file2.Close();
我们来看一下OpenFile的函数定义:
func OpenFile(name string, flag int, perm FileMode) (*File, error)
第一个参数name表示需要打开的文件路径。
第二个参数flag取值如下,可以组合起来用或运算符,表示要以什么权限打开文件。
const (
// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
O_RDONLY int = syscall.O_RDONLY // open the file read-only.
O_WRONLY int = syscall.O_WRONLY // open the file write-only.
O_RDWR int = syscall.O_RDWR // open the file read-write.
// The remaining values may be or'ed in to control behavior.
O_APPEND int = syscall.O_APPEND // append data to the file when writing.
O_CREATE int = syscall.O_CREAT // create a new file if none exists.
O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist.
O_SYNC int = syscall.O_SYNC // open for synchronous I/O.
O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened.
)
第三个参数FileMode为类Unix系统文件组权限值,可以直接设置,比如0755,则表示“-rwxr-xr-x”的文件权限。这个参数表示如果创建了文件,则把该文件权限设置成0755。
Go语言官方建议:绝大多数情况下应该使用Open和Create方法来打开文件和创建文件,因为它们更简洁更直接。Open和Create方法内部其实也是调用了OpenFile来实现的。
打开文件os.Open:
file, error := os.Open(&