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
相关推荐
2401_857622661 小时前
SpringBoot框架下校园资料库的构建与优化
spring boot·后端·php
2402_857589361 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰2 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
ChinaDragonDreamer2 小时前
Kotlin:2.0.20 的新特性
android·开发语言·kotlin
IT良2 小时前
c#增删改查 (数据操作的基础)
开发语言·c#
哎呦没3 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
Kalika0-03 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
_.Switch3 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
代码雕刻家3 小时前
课设实验-数据结构-单链表-文教文化用品品牌
c语言·开发语言·数据结构
一个闪现必杀技3 小时前
Python入门--函数
开发语言·python·青少年编程·pycharm