Go 语言读取文件内容(或逐行读取文件内容)
读取全文(适合小文件内容)
package main
import (
"fmt"
"log"
"os"
)
func main() {
content, err := os.ReadFile("file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(content))
}
输出
Hello World!
This is txt file read by Go!
逐行读取文件内容
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
// open file
f, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
// remember to close the file at the end of the program
defer f.Close()
// read the file line by line using scanner
scanner := bufio.NewScanner(f)
for scanner.Scan() {
// do something with a line
fmt.Printf("line: %s\n", scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
输出
line: Hello World!
line: This is txt file read by Go!
逐字读取文件内容
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
// open file
f, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
// remember to close the file at the end of the program
defer f.Close()
// read the file word by word using scanner
scanner := bufio.NewScanner(f)
scanner.Split(bufio.ScanWords)
for scanner.Scan() {
// do something with a word
fmt.Println(scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
}
输出
Hello
World!
This
is
txt
file
read
by
Go!
分块读取文件(适合大文件读取)
package main
import (
"fmt"
"io"
"log"
"os"
)
const chunkSize = 10
func main() {
// open file
f, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
// remember to close the file at the end of the program
defer f.Close()
buf := make([]byte, chunkSize)
for {
n, err := f.Read(buf)
if err != nil && err != io.EOF {
log.Fatal(err)
}
if err == io.EOF {
break
}
fmt.Println(string(buf[:n]))
}
}
输出
Hello Worl
d!
This is
txt file
read by Go
!
转载自:https://gosamples.dev/read-file/#:~:text=The%20simplest%20way%20of%20reading%20a%20text%20or,the%20file%20line%20by%20line%20or%20in%20chunks.