读文件
一次读完整个文件
- 使用
os.ReadFile
方法
Go
func ReadFile(name string) ([]byte, error)
代码示例
要读取的1.txt
文件
Go
你好,go语言
你好hello world
从零开始学习go
Go
// 一次性全部读取
// func ReadFile(name string) ([]byte, error)
func demo1() {
file, err := os.ReadFile("1.txt");
if err != nil {
fmt.Println("os.ReadFile err", err)
return
}
fmt.Println(string(file))
}
func main() {
demo1()
// 打印如下
// 你好,go语言
// 你好hello world
// 从零开始学习go
}
读取指定长度(单位:字节)
使用
os.OpenFile
和file.Read
中文汉字
和中文符号
为3个字节
,英文字母
和英文符号
为1个字节
如果打开文件,读取完毕后要关闭文件
Go
func OpenFile(name string, flag int, perm FileMode) (*File, error)
代码示例
Go
// 读取指定字节长度
// func OpenFile(name string, flag int, perm FileMode) (*File, error)
// 中文汉字和中文符号为3个字节,英文字母和英文符号为1个字节,
func demo2() {
file, err := os.OpenFile("1.txt", os.O_RDONLY, 0777)
defer file.Close()
if err != nil {
fmt.Println("os.OpenFile", err)
return
}
// 指定读取9个字节
str := make([]byte, 9)
n, err := file.Read(str)
if err != nil {
fmt.Println("file.Read", err)
return
}
fmt.Println("n", n)
fmt.Println("读到的str为:", string(str))
}
func main() {
demo2()
// 打印如下
// n 9
// 读到的str为: 你好,
}
读取片段
使用
Seek
方法指定如何截取片段offset
:表示指针的偏移量
whence
:表示指针移动的方式0
: 从数据头部
开始移动指针;1
: 从指针当前位置
开始移动指针;2
: 从数据尾部
开始移动指针;
Go
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
Go
// 读取片段
// func (f *File) Seek(offset int64, whence int) (ret int64, err error)
// offset 表示指针的偏移量
// whence 表示指针移动的方式
// 0 从数据头部开始移动指针;1 从指针的当前位置开始移动指针;2 从数据的尾部开始移动指针
func demo3() {
file, err := os.OpenFile("1.txt", os.O_RDONLY, 0777)
defer file.Close()
if err != nil {
fmt.Println("os.OpenFile", err)
return
}
str := make([]byte, 9)
file.Seek(9, 0)
n, err := file.Read(str)
if err != nil {
fmt.Println("file.Read", err)
return
}
fmt.Println("n", n)
fmt.Println("读到的str为:", string(str))
}
func main() {
demo3()
// 打印如下
// n 9
// 读到的str为: go语言
}
带缓冲读
使用
bufio.NewReader(file)
除了
reader.ReadLine()
方法,还有reader.ReadString()
,reader.ReadSlice()
,reader.ReadByte()
等当
reader.ReadLine()
返回的err
为io.EOF
说明读完了
Go
func demo5() {
file, err := os.OpenFile("1.txt", os.O_RDONLY, 0777)
defer file.Close() // 读取结束后,需要关闭文件
if err != nil {
fmt.Println("os.OpenFile", err)
return
}
// 使用 bufio.NewReader(file)
reader := bufio.NewReader(file)
for {
line, _, err := reader.ReadLine() // 按行读,每次读取一行
// reader.ReadByte()
if err == io.EOF {
fmt.Println("======读取完毕======")
break
}
fmt.Println(string(line))
}
}
func main() {
demo5()
}