Golang中的文件操作

1.打开文件和关闭文件

Go 复制代码
package main

import (
	"fmt"
	"os"
)

func main() {
	//打开文件
	file, err := os.Open("file/wordtest.txt")
	if err != nil {
		fmt.Println("open file err=", err)
	}

	//file就是一个指针*file
	fmt.Printf("file=%v\n", file)

	//关闭文件
	err = file.Close()
	if err != nil {
		fmt.Println("close file err=", err)
	}
}
Go 复制代码
file=&{0xc000068a00}

2.带缓冲的Reader读取文件

Go 复制代码
package main

//带缓冲的reader读文件
import (
	"bufio"
	"fmt"
	"io"
	"os"
)

//带缓冲的Reader读文件

func main() {
	file, err := os.Open("file/wordtest.txt")
	if err != nil {
		fmt.Println("open file err=", err)
	}
	//当函数推出时,要及时的关闭file
	defer file.Close()

	//创建reader
	reader := bufio.NewReader(file)
	//循环读取文件的内容
	for {
		//读到一个换行结束
		str, err := reader.ReadString('\n')
		//文件的末尾
		if err == io.EOF {
			break
		}
		fmt.Print(str)
	}

	fmt.Println("文件读取结束")
}
Go 复制代码
hello,world
珠海!abc!Golang!
Go,hello,world
文件读取结束

3.一次性读取文件

Go 复制代码
package main

//一次性读取文件
import (
	"fmt"
	"os"
)

// 一次性读取文件
func main() {
	file := "file/wordtest.txt"
	content, err := os.ReadFile(file)
	if err != nil {
		fmt.Printf("read file err=%v", err)
	}
	//[]byte
	fmt.Printf("%v\n", content)
	fmt.Printf("%s\n", string(content))
}
Go 复制代码
[104 101 108 108 111 44 119 111 114 108 100 13 10 231 143 160 230 181 183 239 188 129 97 98 99 33 71 111 108 97 110 103 
33 13 10 71 111 44 104 101 108 108 111 44 119 111 114 108 100 13 10]
hello,world
珠海!abc!Golang!
Go,hello,world

4.创建文件写入内容

Go 复制代码
package main

//创建文件,写入内容
import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	//创建一个新文件,写入5句"hello jinitaimei"
	//1.打开文件
	filePath := "./file/wordtest2.txt"
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
		return
	}
	//
	defer file.Close()
	str := "hello jinitaimei\n"
	//写入时使用带缓存的*writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		writer.WriteString(str)
	}

	//因为Writer是带缓存的,因此再调用WriterString方法时,其实内容是先写入到缓存,所以
	//用flush把缓存的数据真正写入到文件
	writer.Flush()
}
Go 复制代码
wordtest2.txt的文件内容:
hello jinitaimei
hello jinitaimei
hello jinitaimei
hello jinitaimei
hello jinitaimei

5.打开一个存在的文件,把原来的内容覆盖新的内容

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

//打开一个存在的文件,把原来的内容覆盖为10句"Hi,Xiamen"

func main() {
	//创建一个新文件,写入5句"hello jinitaimei"
	//1.打开文件
	filePath := "./file/wordtest2.txt"
	//O_TRUNC:清理内容
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_TRUNC, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
		return
	}
	//
	defer file.Close()
	str := "hello Xiamen\r\n"
	//写入时使用带缓存的*writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 10; i++ {
		writer.WriteString(str)
	}

	//因为Writer是带缓存的,因此再调用WriterString方法时,其实内容是先写入到缓存,所以
	//用flush把缓存的数据真正写入到文件
	writer.Flush()
}

6.对已经存在的文件,追加内容

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

// 对已经存在的文件,追加内容
func main() {
	filePath := "./file/wordtest2.txt"
	file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("open file err=%v\n", err)
		return
	}

	//及时关闭file指针
	defer file.Close()

	str := "Humans, I want the clear,pollution-free water!\r\n"
	//使用带缓存的*Writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 10; i++ {
		writer.WriteString(str)
	}

	writer.Flush()
}

7.把原来的内容读取出来,再往文件追加几句话

Go 复制代码
package main

//把原来的内容读取出来,追加几句话
import (
	"bufio"
	"fmt"
	"io"
	"os"
)

// 对已经存在的文件,追加内容
func main() {
	filePath := "./file/wordtest2.txt"
	file, err := os.OpenFile(filePath, os.O_RDWR|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("open file err=%v\n", err)
		return
	}

	//及时关闭file指针
	defer file.Close()
	//先读取原来文件的内容,显示在终端
	reader := bufio.NewReader(file)
	for {
		str2, err := reader.ReadString('\n')
		//文件末尾
		if err == io.EOF {
			break
		}
		fmt.Print(str2)
	}

	str := "Sweet dolphins, I wish you all peace.\r\n"
	//使用带缓存的*Writer
	writer := bufio.NewWriter(file)
	for i := 0; i < 5; i++ {
		writer.WriteString(str)
	}

	writer.Flush()
}
Go 复制代码
终端:
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!

文件:
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Humans, I want the clear,pollution-free water!
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.
Sweet dolphins, I wish you all peace.

8.把一个文件的内容追加到另一个文件中

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	//1.将word1.txt的内容读到内存
	//2.将word1.txt的内容写入word2.txt
	filePath1 := "./file/word1.txt"
	filePath2 := "./file/word2.txt"
	content, err := os.ReadFile(filePath1)
	if err != nil {
		//说明文件有错误
		fmt.Printf("read file err=%v\n", err)
		return
	}

	word2_file, err := os.OpenFile(filePath2, os.O_RDWR|os.O_APPEND, 0666)
	writer := bufio.NewWriter(word2_file)
	writer.WriteString(string(content))
	writer.Flush()

}
Go 复制代码
word1.txt:
When spring comes, all the seeds begin to burgeon.

word2.txt:
People wait in the lounge for boarding.

运行结果:
People wait in the lounge for boarding.When spring comes, all the seeds begin to burgeon.

9.拷贝文件到另一个目录中

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

// 将.jpg从D盘拷贝到E盘
//
//	<----
func CopyFile(dstFileName string, srcFileName string) (written int64, err error) {
	srcFile, err := os.Open(srcFileName)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
	}
	//通过srcFile获取的Reader
	reader := bufio.NewReader(srcFile)

	//打开dstFile
	dstFile, err := os.OpenFile(dstFileName, os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
	}
	//通过dstFile获取到Writer
	writer := bufio.NewWriter(dstFile)
	//<---
	return io.Copy(writer, reader)
}

func main() {
	//调用CopyFile完成文件拷贝
	srcFile := "d:/goldpig.jpg"
	dstFile := "e:/goldpig.jpg"
	_, err := CopyFile(dstFile, srcFile)
	if err == nil {
		fmt.Println("拷贝完成")
	} else {
		fmt.Printf("拷贝错误 err=%v\n", err)
	}
}

10.统计文件中不同类型的字符的数量

Go 复制代码
package main

import (
	"bufio"
	"fmt"
	"io"
	"os"
)

//统计文件中不同类型的字符个数

// 定义一个结构体,用于保存统计结果
type CharCount struct {
	ChCount    int //记录英文个数
	NumCount   int //记录数字的个数
	SpaceCount int //记录空格的个数
	OtherCount int //记录其他字符个数
}

func main() {
	//打开一个文件,创一个Reader
	//每读取一行,就统计该行有多少个英文、数字、空格和其他字符
	//然后将结果保存到一个结构体
	fileName := "./file/abc.txt"
	file, err := os.Open(fileName)
	if err != nil {
		fmt.Printf("open file err=%v\n", err)
		return
	}
	defer file.Close()
	//定义个CharCount示例
	var count CharCount
	//创建一个Reader
	reader := bufio.NewReader(file)

	//开始循环的读取fileName的内容
	for {
		str, err := reader.ReadString('\n')
		//读到文件末尾就退出
		if err == io.EOF {
			break
		}
		//遍历str,进行统计
		for _, v := range str {
			switch {
			case v >= ('a') && v <= 'z':
				fallthrough
			case v >= 'A' && v <= 'Z':
				count.ChCount++
			case v == ' ' || v == '\t':
				count.SpaceCount++
			case v >= '0' && v <= '9':
				count.NumCount++
			default:
				count.OtherCount++
			}
		}
	}

	//输出统计的结果看看是否正确
	fmt.Printf("字符的个数=%v 数字的个数=%v 空格的个数=%v 其他字符的个数=%v\n",
		count.ChCount, count.NumCount, count.SpaceCount, count.OtherCount)
}
Go 复制代码
文件内容:
ab123 89popj
yy89 hello

运行结果:
字符的个数=13 数字的个数=7 空格的个数=2 其他字符的个数=4
相关推荐
whyfail2 分钟前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
麻瓜老宋36 分钟前
AI开发C语言应用按步走,表达式计算器calc的第二十三步,多行输入、进制输出、错误恢复、常量折叠、配置加载等
c语言·开发语言·atomcode
q567315231 小时前
企业级 HTTP 代理采购选型:技术评估清单 15 项
开发语言·网络·爬虫·网络协议·http·隧道ip·代理ip
Muscleheng1 小时前
Spring Boot 3.x 集成 DeepSeek 实现 Function Calling(工具调用)
人工智能·spring boot·后端·ai·spring ai·deepseek
@航空母舰1 小时前
SpringBoot通过Map实现天然的策略模式
java·spring boot·后端
天天进步20152 小时前
Python全栈项目--智能办公自动化系统
开发语言·python
IT_陈寒2 小时前
JavaScript的this又双叒叕让我怀疑人生了
前端·人工智能·后端
陈随易2 小时前
MCP协议第5次更新,从打电话到微信聊天的巨大变革
前端·后端·程序员
65岁退休Coder2 小时前
LangChain v1.3.4 笔记 - 06 RAG 检索增强生成
后端
cm04Z9c912 小时前
C#摸鱼实录——IoC与DI案例详解
开发语言·c#