docs: file 文件读取

This commit is contained in:
Shikong 2021-10-04 15:33:13 +08:00
parent d94d3606e1
commit b596fd5f6b

74
base/file/main.go Normal file
View File

@ -0,0 +1,74 @@
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
)
// 文件操作
func main() {
// 获取 go 安装目录
cmd := exec.Command("go", "env", "GOROOT")
out, _ := cmd.Output()
goPath := strings.Replace(string(out), "\n", "", -1)
f, err := os.Open(path.Join(goPath, "LICENSE"))
if err != nil {
fmt.Println(err)
os.Exit(-1)
}
defer func() {
_ = f.Close()
}()
// 原始方法读取文件
for {
// 读文件
buf := make([]byte, 256)
read, err := f.Read(buf)
if err == io.EOF {
fmt.Println("读取完毕")
break
}
if err != nil {
return
}
fmt.Printf("读取 %d 字节, 内容 => \n%s \n", read, buf)
}
// 重置文件指针
_, _ = f.Seek(0, 0)
fmt.Println("=========================================================")
// bufio 读取文件
reader := bufio.NewReader(f)
for {
line, err := reader.ReadString('\n')
if err == io.EOF {
fmt.Println("读取完毕")
break
}
if err != nil {
return
}
fmt.Printf("读取内容 => \n%s", line)
}
_, _ = f.Seek(0, 0)
fmt.Println("=========================================================")
// 使用 ioutil 读取整个文件
buf, _ := ioutil.ReadAll(f)
fmt.Printf("读取内容 => \n%s", buf)
}