1)概念
2)
package main
import(
"fmt"
"os"
)
func main(){
file,err:=os.Open("d:/test.txt")
if err!=nil{
fmt.Println("open err",err)
}
fmt.Println("file=",file)
err=file.Close()
if err!=nil{
fmt.Println("close err",err)
}
}
二、读文件操作应用实例
1)带缓存
package main
import(
"fmt"
"os"
"bufio"
"io"
)
func main(){
file,err:=os.Open("d:/test.txt")
if err!=nil{
fmt.Println("open err",err)
}
defer file.Close()
reader:=bufio.NewReader(file)
for{
content,err:=reader.ReadString('\n')
if err==io.EOF{
break
}
fmt.Print(content)
}
fmt.Println("文件读取结束")
}
2)不带缓存
package main
import(
"fmt"
"io/ioutil"
)
func main(){
file:="d:/test.txt"
content,err:=ioutil.ReadFile(file)
if err!=nil{
fmt.Println("read err ",err)
}
fmt.Printf("%v",string(content))
}
三、写文件操作应用实例
package main
import(
"fmt"
"bufio"
"os"
)
func main(){
filePath:="d:/a.txt"
file,err:=os.OpenFile(filePath,os.O_WRONLY|os.O_CREAT,0666)
if err!=nil{
fmt.Println("open err",err)
}
defer file.Close()
str:="hello world\n"
writer:=bufio.NewWriter(file)
for i:=0;i<5;i++{
writer.WriteString(str)
}
writer.Flush()
}
使用 ioutil.ReadFile / ioutil.WriteFile 完成写文件的任务
package main
import(
"fmt"
"os"
"bufio"
"io"
)
func main(){
filePath:="d:/test.txt"
file,err:=os.OpenFile(filePath,os.O_WRONLY|os.O_APPEND,0666)
if err!=nil{
fmt.Println("open err",err)
return
}
defer file.Close()
reader:=bufio.NewReader(file)
for{
content,err:=reader.ReadString('\n')
if err==io.EOF{
break
}
fmt.Print(content)
}
writer:=bufio.NewWriter(file)
str:="hello,北京\n"
for i:=0;i<5;i++{
writer.WriteString(str)
}
writer.Flush()
}
四、文件编程实例
拷贝文件
package main
import(
"fmt"
"os"
"io"
"bufio"
)
func CopyFile(des string ,src string)(written int64,err error){
s,err:=os.Open(src)
if err!=nil(
fmt.Println("open err",err)
)
defer s.Close()
reader:=bufio.NewReader(s)
// for{
// content,err:=reader.ReadString('\n')
// if err==io.EOF{
// break
// }
// fmt.Print(content)
// }
d,err:=os.OpenFile(des,os.O_WRONLY|os.O_CREAT,0666)
if err!=nil(
fmt.Println("open err2",err)
return
)
writer:=bufio.WriteString(d)
defer d.Close()
return io.Copy(writer,reader)
}
func main(){
src:="d:/test.txt"
dest:="d:/abc.txt"
-,err:=CopyFile(src,dest)
if err==nil{
fmt.Println("拷贝完成")
}else{
fmt.Println("拷贝失败",err)
}
}
五、命令行参数
1)说明
2)代码
func main(){
fmt.Println("命令行的参数",len(os.Args))
for i,v:=range os.Args{
fmt.Printf("Args[%v]=%v\n",i,v)
}
}
六、JSON基本介绍
1)介绍
2)格式
对于结构体的序列化,如果我们希望序列化后的 key的名字,又我们自己重新制定,那么可以给struct指定一个 tag 标签
package main
import(
"fmt"
"encoding/json"
)
type Monster struct{
Name string`json:"name"`
Age int`json:"age"`
Birthday string`json:"birthday"`
Sal float64
Skill string
}
func testStruct(){
monster:=Monster{
Name:"牛魔王",
Age : 500,
Birthday : "2011-11-11",
Sal : 8000.0,
Skill : "牛魔拳",
}
data ,err:=json.Marshal(&monster)
if err!=nil{
fmt.Println("序列化失败:",err)
}
fmt.Println("monster序列化之后的结果=%v\n",string(data))
}
func testMap(){
var a map[string]interface{}
a=make(map[string]interface{})
a["name"] = "红孩儿"
a["age"] = 30
a["address"] = "洪崖"
data,err:=json.Marshal(a)
if err!=nil{
fmt.Println("序列化失败:",err)
}
fmt.Printf("map序列化后=%v\n",string(data))
}
func testSlice(){
var slice []map[string]interface{}
var m1 map[string]interface{}
m1=make(map[string]interface{})
m1["name"] = "jack"
m1["age"] = "7"
m1["address"] = "北京"
slice = append(slice,m1)
var m2 map[string]interface{}
m2=make(map[string]interface{})
m2["name"] = "tom"
m2["age"] = "20"
m2["address"] = [2]string{"墨西哥","夏威夷"}
slice = append(slice,m2)
data ,err:=json.Marshal(slice)
if err!=nil{
fmt.Println("序列化失败:",err)
}
fmt.Printf("slice序列化后=%v\n",string(data))
}
func main(){
testStruct()
testMap()
testSlice()
}
八、JSON的反序列化
package main
import(
"fmt"
"encoding/json"
)
type Monster struct {
Name string
Age int
Birthday string //.... Sal float64
Skill string
}
func unmarshalSturct(){
str:= "{\"Name\":\"牛魔王\",\"Age\":500,\"Birthday\":\"2011-11-11\",\"Sal\":8000,\"Skill\":\"牛魔拳\"}"
var monster Monster
err:=json.Unmarshal([]byte(str),&monster)
if err!=nil{
fmt.Printf("unmarshal err=%v\n", err)
}
fmt.Printf("反序列化后:monster=%v\n",monster)
}
func unmarshalMap(){
str := "{\"address\":\"洪崖洞\",\"age\":30,\"name\":\"红孩儿\"}"
var a map[string]interface{}
err:=json.Unmarshal([]byte(str),&a)
if err!=nil{
fmt.Printf("unmarshal err=%v\n", err)
}
fmt.Printf("反序列化后:a=%v\n",a)
}
func unmarshalSlice(){
str:= "[{\"address\":\"北京\",\"age\":\"7\",\"name\":\"jack\"}," +
"{\"address\":[\"墨西哥\",\"夏威夷\"],\"age\":\"20\",\"name\":\"tom\"}]"
var slice []map[string]interface{}
err:=json.Unmarshal([]byte(str),&slice)
if err!=nil{
fmt.Printf("unmarshal err=%v\n", err)
}
fmt.Printf("反序列化后:slice=%v\n",slice)
}
func main(){
unmarshalSturct()
unmarshalMap()
unmarshalSlice()
}
总结
本文仅仅简单介绍了Golang文件操作,此篇是通过b站尚硅谷Golang视频的学习做的笔记。