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
相关推荐
liangshanbo12156 小时前
手写 Function.prototype.call 与 Function.prototype.apply 面试题满分答案
开发语言·javascript·原型模式
Zenova EdgeOS6 小时前
C++ 工业边缘 libcurl HTTP 客户端实战
开发语言·c++·网络协议·边缘计算
GoGeekBaird6 小时前
从「跑完即销毁」到「用完再销毁」:云沙箱的一次进化
后端·github·ai编程
Jackson_GJH7 小时前
Qt 右键自定义菜单的实现
开发语言·c++·qt
孫治AllenSun7 小时前
【LangChain4J-09】开发学习知识点
spring boot·后端·学习
CoderYanger7 小时前
前端基础——JavaScript(WebAPI)(下篇)
java·开发语言·前端·javascript·程序人生·面试·职场和发展
lisin-lee-cooper7 小时前
简单聊聊 Spring 框架源码
java·后端·spring
复方金银花颗粒7 小时前
reactor和proactor的好处和坏处。为什么要用reactor而不用 proactor?
后端·信号处理
IT_陈寒8 小时前
JavaScript的这个隐式转换特性差点让我加班到凌晨
前端·人工智能·后端
小木_.8 小时前
Python 离线识别滑块缺口距离,项目推荐
开发语言·python·滑块识别·人机验证·滑块缺口·缺口识别