golang文件读写操作
推荐使用ioutil读写
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
read1()
}
func write1(){
content := []byte("1111hello golang")
err := ioutil.WriteFile("logs/output.txt", content, 0666)
if err != nil {
fmt.Println("ioutil WriteFile error: ", err)
}
}
func read1() {
file, err := os.Open("logs/2021-02-07.log")
if err != nil {
panic(err)
}
defer file.Close()
content, err := ioutil.ReadAll(file)
fmt.Println(string(content))
}
func read2() {
filepath := "logs/2021-02-07.log"
content ,err :=ioutil.ReadFile(filepath)
if err !=nil {
panic(err)
}
fmt.Println(string(content))
}
func checkFileIsExist(filename string) bool {
var exist = true
if _, err := os.Stat(filename); os.IsNotExist(err) {
exist = false
}
return exist
}
文件其他操作示例
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"time"
)
func main() {
filewriteApp("{\"d\":[{\"ct\":1623139822000,\"shengzhijil\":9.31,\"zuzhijilu\":10.12}],\"g\":\"T0006.A\",\"id\":\"omldeviceID\",\"t\":1623139822302,\"v\":1}")
filew()
}
func filewriteApp(str_content string) {
fd,_:=os.OpenFile("test3.log",os.O_RDWR|os.O_CREATE|os.O_APPEND,0644)
fd_time:=time.Now().Format("2006-01-02 15:04:05");
fd_content:=strings.Join([]string{"======",fd_time,"=====",str_content,"\n"},"")
buf:=[]byte(fd_content)
fd.Write(buf)
fd.Close()
}
func filew() {
fi, err := os.Open("test3.log")
if err != nil {
fmt.Printf("Error: %s\n", err)
return
}
defer fi.Close()
br := bufio.NewReader(fi)
for {
a, _, c := br.ReadLine()
if c == io.EOF {
break
}
fmt.Println(string(a))
fmt.Println("=====")
}
}
func FileWrite(fileName string, data []byte) bool {
err := ioutil.WriteFile(fileName, data, 0666)
if err != nil {
log.Println("FileWrite ioutil WriteFile error: ", err)
return false
}
return true
}
func FileRead(filepath string) []byte {
content, err := ioutil.ReadFile(filepath)
if err != nil {
log.Println("FileRead ioutil ReadFile error: ", err)
}
return content
}