当前位置:网站首页>常见的Go写文件方式
常见的Go写文件方式
2022-07-17 00:08:00 【祥仔先生】
package main
import (
"bufio" //缓存IO
"fmt"
"io"
"io/ioutil" //io 工具包
"os"
)
func check(e error) {
if e != nil {
panic(e)
}
}
/**
* 判断文件是否存在 存在返回 true 不存在返回false
*/
func checkFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
func main() {
var wireteString = "测试n"
var filename = "./output1.txt"
var f *os.File
var err1 error
/***************************** 第一种方式: 使用 io.WriteString 写入文件 ***********************************************/
if checkFileIsExist(filename) { //如果文件存在
f, err1 = os.OpenFile(filename, os.O_APPEND, 0666) //打开文件
fmt.Println("文件存在")
} else {
f, err1 = os.Create(filename) //创建文件
fmt.Println("文件不存在")
}
check(err1)
n, err1 := io.WriteString(f, wireteString) //写入文件(字符串)
check(err1)
fmt.Printf("写入 %d 个字节n", n)
/***************************** 第二种方式: 使用 ioutil.WriteFile 写入文件 ***********************************************/
var d1 = []byte(wireteString)
err2 := ioutil.WriteFile("./output2.txt", d1, 0666) //写入文件(字节数组)
check(err2)
/***************************** 第三种方式: 使用 File(Write,WriteString) 写入文件 ***********************************************/
f, err3 := os.Create("./output3.txt") //创建文件
check(err3)
defer f.Close()
n2, err3 := f.Write(d1) //写入文件(字节数组)
check(err3)
fmt.Printf("写入 %d 个字节n", n2)
n3, err3 := f.WriteString("writesn") //写入文件(字节数组)
fmt.Printf("写入 %d 个字节n", n3)
f.Sync()
/***************************** 第四种方式: 使用 bufio.NewWriter 写入文件 ***********************************************/
w := bufio.NewWriter(f) //创建新的 Writer 对象
n4, err3 := w.WriteString("bufferedn")
fmt.Printf("写入 %d 个字节n", n4)
w.Flush()
f.Close()
}边栏推荐
猜你喜欢

Countless times of stepping on the pit to install awvs

NFT单月万倍神话,元宇宙之门的奥秘是什么?

数据指标体系如何搭建才最有效,从0到1带你快速入门丨02期直播回顾

TCP and UDP, TCP server and client, UDP server and client

NameNode 和 SecondaryNameNode

Scala environment construction

Deep copy and shallow copy

Dhfs read / write process

Solve the problem that Scala cannot initialize the class of native

What is the QS module?
随机推荐
fetch请求-简单记录
El form special character verification
Punch in 10 interview questions every day - JVM article
Database programming (MySQL) of node, adding, deleting, modifying and querying
字节二面:什么是伪共享?如何避免?
安全多方计算体系架构及应用思考
蛟分承影,雁落忘归——袋鼠云一站式全自动化运维管家ChengYing(承影)正式开源
MapReduce环境准备
软件漏洞分析入门(四)
每日10道面试题打卡——JVM篇
08-BTC-分叉
iptables和snort基本配置
Today's code farmer girl learned about nodejs and repl interactive interpreter
金融学 杂项记录
Uniapp development, upload pictures in the app and send them directly to OSS
The platform of digital collection NFT is good
nft发行价格是多少(解读NFT建立起NFT世界观)
Redis+Caffeine两级缓存,让访问速度纵享丝滑
量子计算机带来的全新通信安全风险分析及应对建议
NFT differentiation trend has shown, how to capture value?