package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
)
// 一次性写入所有文件
func writeAllFile() {
// 要写入的文件地址和名称 index.html
filePath := "/test/file/write/index.html"
// 要写入的文件内容
content := "测试写入文件内容"
// 这种方式写入文件,如果文件不存在则创建该文件
// 如果文件已存在,则进行覆盖写入
err := os.WriteFile(filePath, []byte(content), 0666)
if err != nil {
fmt.Printf("write file err, %v", err)
}
fmt.Println("write file success")
}
// 用带有缓存方式进行写入文件内容
// 创建文件,并写入
func createFileBuf() {
filePath := "/test/file/write/create.html"
// os.O_WRONLY write-only
// os.O_CREATE 如果文件不存在则创建
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("OpenFile() file err, %v", err)
}
// 关闭文件句柄
defer file.Close()
// 创建一个writer
writer := bufio.NewWriter(file)
content := "测试create.html写入文件\n"
_, err = writer.WriteString(content)
if err != nil {
fmt.Printf("write file err, %v", err)
}
// 最后真正写入文件
writer.Flush()
fmt.Println("write file success")
}
// 追加写入文件内容
func appendFileBuf() {
filePath := "/test/file/write/create.html"
// os.APPEND 追加写入文件内容
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
fmt.Printf("OpenFile() file err, %v", err)
}
// 关闭文件句柄
defer file.Close()
// 创建 writer
writer := bufio.NewWriter(file)
// 写入的文件内容
content := "追加文件测试内容\n"
_, err = writer.WriteString(content)
if err != nil {
fmt.Printf("append file err, %v", err)
}
writer.Flush()
fmt.Println("append file success")
}
// 拷贝图片文件
func copyPic() bool {
// 源文件
srcFilePath := "/test/file/write/cover.jpg"
// 拷贝后生成的文件
dstFilePath := "/test/file/write/copy.jpg"
// 打开源文件
srcFile, err := os.Open(srcFilePath)
if err != nil {
fmt.Printf("open src file err, %v", err)
return false
}
// 关闭源文件句柄
defer srcFile.Close()
// 获取源文件的 reader
reader := bufio.NewReader(srcFile)
// 创建目标文件
dstFile, err := os.OpenFile(dstFilePath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("open dst file err, %v", err)
return false
}
// 关闭目标文件句柄
defer dstFile.Close()
// 获取 writer
writer := bufio.NewWriter(dstFile)
// 进行文件拷贝
_, err = io.Copy(writer, reader)
if err != nil {
fmt.Printf("copy file err, %v", err)
return false
}
fmt.Println("copy file success")
return true
}
// 使用 io/ioutil 包写入文件
func writeIoUtil() {
// 写入的文件地址
filePath := "/test/file/write/ioutil.html"
// 写入的文件内容
content := "测试写入文件,使用io/ioutil包进行文件的写入操作"
err := ioutil.WriteFile(filePath, []byte(content), 0666)
if err != nil {
fmt.Printf("write file err, %v\n", err)
}
fmt.Println("write file success")
}
// 文件的写操作
func main() {
// 一次性写入全部文件
writeAllFile()
// 创建文件并写入,以缓存方式
createFileBuf()
// 追加写入文件
appendFileBuf()
// 拷贝图片
copyPic()
// 使用 io/ioutil 进行文件写入
writeIoUtil()
}
golang写入字符串文件
于 2022-04-18 11:20:03 首次发布