Golang中的文件操作

1.打开文件和关闭文件

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)
	}
}
file=&{0xc000068a00}

2.带缓冲的Reader读取文件

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("文件读取结束")
}
hello,world
珠海!abc!Golang!
Go,hello,world
文件读取结束

3.一次性读取文件

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))
}
[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.创建文件写入内容

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()
}
wordtest2.txt的文件内容:
hello jinitaimei
hello jinitaimei
hello jinitaimei
hello jinitaimei
hello jinitaimei

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

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.对已经存在的文件,追加内容

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.把原来的内容读取出来,再往文件追加几句话

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()
}
终端:
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.把一个文件的内容追加到另一个文件中

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()

}
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.拷贝文件到另一个目录中

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.统计文件中不同类型的字符的数量

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)
}
文件内容:
ab123 89popj
yy89 hello

运行结果:
字符的个数=13 数字的个数=7 空格的个数=2 其他字符的个数=4

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值