一、基本读写
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("/Users/m73/Desktop/gocod/go.mod")
if err != nil {
fmt.Println("open file err = ", err)
}
fmt.Print("file=%v ", file)
err = file.Close()
if err != nil {
fmt.Println("close file err = ",err)
}
}
二、带缓冲区的读取
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func main(){
file, err := os.Open("/Users/m73/Desktop/gocod/go.mod")
if err != nil {
fmt.Println("open file err = ", err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
break
}
fmt.Print(str)
}
fmt.Println("文件读取结束...")
}
三、一次性读取
package main
import (
"fmt"
"io/ioutil"
)
func main() {
file := "/Users/m73/Desktop/gocod/go.mod"
content, err := ioutil.ReadFile(file)
if err != nil {
fmt.Printf("read file err = %v \n",err)
}
fmt.Printf("%v", string(content) )
}
四、写入
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
filepath := "/Users/m73/Desktop/gocod/go.mod1"
file, err := os.OpenFile(filepath, os.O_WRONLY | os.O_CREATE,0666)
if err != nil {
fmt.Printf("open file err = %v\n",err)
}
defer file.Close()
str := "hello,Gardon\n"
writer := bufio.NewWriter(file)
for i := 0;i < 5; i++ {
writer.WriteString(str)
}
writer.Flush()
}
五、写入的四种方式
-
写入前清空数据
package main import ( "bufio" "fmt" "os" ) func main() { filepath := "/Users/m73/Desktop/gocod/go.mod1" file, err := os.OpenFile(filepath, os.O_WRONLY | os.O_TRUNC,0666) if err != nil { fmt.Printf("open file err = %v\n",err) } defer file.Close() str := "你好猪猪\r\n" writer := bufio.NewWriter(file) for i := 0;i < 10; i++ { writer.WriteString(str) } writer.Flush() }
-
追加
package main import ( "bufio" "fmt" "io" "os" ) func main() { filepath := "/Users/m73/Desktop/gocod/go.mod1" file, err := os.OpenFile(filepath, os.O_RDWR | os.O_APPEND,0666) if err != nil { fmt.Printf("open file err = %v\n",err) } defer file.Close() reader := bufio.NewReader(file) for { str, err := reader.ReadString('\n') if err == io.EOF { break } fmt.Println(str) } str1 := "你好猪猪2\r\n" writer := bufio.NewWriter(file) for i := 0;i < 10; i++ { writer.WriteString(str1) } writer.Flush() }
-
将文件备份
package main import ( "fmt" "io/ioutil" ) func main() { filepath1 := "/Users/m73/Desktop/gocod/go.mod1" filepath2 := "/Users/m73/Desktop/gocod/go.mod2" data, err := ioutil.ReadFile(filepath1) if err != nil { fmt.Printf("read file err=%v",err) return } err = ioutil.WriteFile(filepath2, data, 0666) if err != nil { fmt.Printf("write file error=%v\n",err) } }
六、判断文件或目录存在
package main
import (
"fmt"
"io/ioutil"
"os"
)
func PathExists(path string)(bool, error){
_, err := os.Stat(path)
if err == nil {
fmt.Println("文件或目录存在")
return true,nil
}
if os.IsNotExist(err){
fmt.Println("文件或目录不存在")
return false, nil
}
fmt.Println("不确定是否存在")
return false, err
}
func main() {
filepath1 := "/Users/m73/Desktop/gocod/go.mod1"
filepath2 := "/Users/m73/Desktop/gocod/go.mod2"
filepath3 := "/Users/m73/Desktop/gocod/go.mod3"
PathExists(filepath3)
data, err := ioutil.ReadFile(filepath1)
if err != nil {
fmt.Printf("read file err=%v",err)
return
}
err = ioutil.WriteFile(filepath2, data, 0666)
if err != nil {
fmt.Printf("write file error=%v\n",err)
}
}
七、拷贝文件
package main
import (
"bufio"
"fmt"
"io"
"os"
)
func CopyFile(dstFilename string, srcFilename string)(written int64, err error){
srcfile, err := os.Open(srcFilename)
if err != nil {
fmt.Printf("open fiel error%v\n",err)
}
defer srcfile.Close()
reader := bufio.NewReader(srcfile)
dstfile, err := os.OpenFile(dstFilename, os.O_WRONLY | os.O_CREATE, 0666)
if err != nil {
fmt.Printf("open file err=%v\n",err)
return
}
writer := bufio.NewWriter(dstfile)
defer dstfile.Close()
return io.Copy(writer, reader)
}
func main() {
filepath1 := "/Users/m73/Desktop/gocod/kvm.png"
filepath2 := "/Users/m73/Desktop/gocod/2.png"
_, err := CopyFile(filepath2,filepath1)
if err == nil {
fmt.Println("拷贝完成")
} else {
fmt.Printf("拷贝错误 err= %v ",err)
}
}
八、统计字符个数
package main
import (
"bufio"
"fmt"
"io"
"os"
)
type CharCount struct {
ChCount int
NumCount int
SpaceCount int
OtherCount int
}
func main() {
fileName := "/Users/m73/Desktop/gocod/go.mod"
file, err := os.Open(fileName)
if err != nil {
fmt.Printf("open file err=%v\n",err)
return
}
defer file.Close()
var count CharCount
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
break
}
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",count.ChCount,count.NumCount,count.SpaceCount,count.OtherCount)
}
九、命令行
TODU
十、JSon
-
序列化
package main import ( "encoding/json" "fmt" ) type Monster struct { Name string `json:"name"` Age int `json:"age"` Birthday string `json:"birthday"` Sal float64 `json:"sal"` Skill string `json:"skill"` } func testStruct() { monster := Monster{ Name: "牛魔王", Age: 500, Birthday: "2111-11-11", Sal: 9999999.0, Skill: "盖塔波动拳", } data, err := json.Marshal(&monster) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) } fmt.Printf("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.Printf("序列化错误 err=%v\n", err) } fmt.Printf("a map 序列化后= %v\n", string(data)) } func testSlice() { var slice []map[string]interface{} var m1 map[string]interface{} m1 = make(map[string]interface{}) m1["name"] = "bk" m1["age"] = 7 m1["address"] = "北京" slice = append(slice, m1) var m2 map[string]interface{} m2 = make(map[string]interface{}) m2["name"] = "dk" m2["age"] = 22 m2["address"] = [2]string{"上海","腊梅"} slice = append(slice, m2) data, err := json.Marshal(slice) if err != nil { fmt.Printf("序列化错误 err=%v\n", err) } fmt.Printf("a map 序列化后= %v\n", string(data)) } func main() { testStruct() testMap() testSlice() }
monster序列化后={"Name":"牛魔王","Age":500,"Birthday":"2111-11-11","Sal":9999999,"Skill":"盖塔波动拳"} a map 序列化后= {"address":"星际","age":30,"name":"韩萧"} a map 序列化后= [{"address":"北京","age":7,"name":"bk"},{"address":["上海","腊梅"],"age":22,"name":"dk"}]
-
反序列化
package main import ( "encoding/json" "fmt" ) type Monster struct { Name string Age int Birthday string Sal float64 Skill string } func unmarshalStruct() { str := "{\"Name\":\"牛魔王\",\"Age\":500,\"Birthday\":\"2111-11-11\",\"Sal\":9999999,\"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 := "{\"Name\":\"牛魔王\",\"Age\":500,\"Birthday\":\"2111-11-11\",\"Sal\":9999999,\"Skill\":\"盖塔波动拳\"}" var a map[string]interface{} err := json.Unmarshal([]byte(str), &a) if err != nil { fmt.Printf("unmarshal err=%v\n", err) } fmt.Printf("反序列化后 monster=%v\n", a) } func main() { unmarshalStruct() unmarshalMap() }