一. 基本案例
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main() {
fmt.Println("-----------------------------------")
fmt.Println("-----------------------------------")
fmt.Println("----------------写出文件-------------------")
fmt.Println("-----------------------------------")
test06()
}
func test06() {
filepath := "d:/abc.txt"
file, err := os.OpenFile(filepath, os.O_RDWR, 0666)
if err != nil {
fmt.Println(err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
readString, err := reader.ReadString('\n')
if err == io.EOF {
break
}
fmt.Print(readString)
}
writer := bufio.NewWriter(file)
for i := 0; i < 5; i++ {
writer.WriteString("我是djjjjjjjjjjjjjj~~~\n")
}
writer.Flush()
}
func test05() {
filepath := "d:/abc.txt"
file, err := os.OpenFile(filepath, os.O_WRONLY|os.O_APPEND, 666)
defer file.Close()
if err != nil {
fmt.Println(err)
}
writer := bufio.NewWriter(file)
for i := 0; i < 10; i++ {
writer.WriteString("我是灰灰灰~💴🔪999\n")
}
writer.Flush()
}
func test04() {
filepath := "d:/abc.txt"
file, err := os.OpenFile(filepath, os.O_WRONLY|os.O_TRUNC, 666)
defer file.Close()
if err != nil {
fmt.Println(err)
}
writer := bufio.NewWriter(file)
for i := 0; i < 10; i++ {
writer.WriteString("我是渣渣灰~一🔪999\n")
}
writer.Flush()
}
func test03() {
filepath := "d:/abc.txt"
file, err := os.OpenFile(filepath, os.O_WRONLY|os.O_CREATE, 0666)
defer file.Close()
if err != nil {
fmt.Println(err)
}
writer := bufio.NewWriter(file)
str := "Hello coderyeah!\n"
for i := 0; i < 5; i++ {
writeString, _ := writer.WriteString(str)
fmt.Println(writeString)
}
writer.Flush()
fmt.Println("写入完成")
}
func test02() {
filePath := "d:/testgo.txt"
str, err := os.ReadFile(filePath)
if err != nil {
fmt.Println(err)
}
fmt.Print(string(str))
}
func test01() {
file, err := os.Open("d:/testgo.txt")
if err != nil {
fmt.Println(err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
fmt.Println(err)
break
}
fmt.Print(str)
}
fmt.Println("文件读取结束")
}
func test00() {
file, err := os.Open("d:/testgo.txt")
if err != nil {
fmt.Println(err)
}
fmt.Println(file)
var b []byte
b = make([]byte, 50)
for {
n, err := file.Read(b)
fmt.Println(n, string(b[:n]))
if err != nil {
if err == io.EOF {
fmt.Println("EOF:", err)
} else {
fmt.Println("err:", err)
}
break
}
}
defer func(file *os.File) {
err := file.Close()
if err != nil {
fmt.Println(err)
}
}(file)
}