文件处理
Json
package main
import (
"encoding/json"
"fmt"
"os"
)
type Website struct {
Name string `xml:"name,attr"`
Url string
Course []string
}
func write() {
info := []Website{{"Golang", "http://www.ibug.info/golang/", []string{"http://www.ibug.info/cplus/", "http://www.ibug.info/linux_tutorial/"}}, {"Java", "http://www.ibug.info/java/", []string{"http://www.ibug.info/socket/", "http://www.ibug.info/python/"}}}
filePtr, err := os.Create("info.json")
if err != nil {
fmt.Println("文件创建失败", err.Error())
return
}
defer filePtr.Close()
encoder := json.NewEncoder(filePtr)
err = encoder.Encode(info)
if err != nil {
fmt.Println("编码错误", err.Error())
} else {
fmt.Println("编码成功")
}
}
func read() {
filePtr, err := os.Open("./info.json")
if err != nil {
fmt.Println("文件打开失败 [Err:%s]", err.Error())
return
}
defer filePtr.Close()
var info []Website
decoder := json.NewDecoder(filePtr)
err = decoder.Decode(&info)
if err != nil {
fmt.Println("解码失败", err.Error())
} else {
fmt.Println("解码成功")
fmt.Println(info)
}
}
Xml
package main
import (
"encoding/xml"
"fmt"
"os"
)
type Website struct {
Name string `xml:"name,attr"`
Url string
Course []string
}
func write() {
info := Website{"Golang", "http://www.ibug.info/golang/", []string{"Go语言入门教程", "Golang入门教程"}}
f, err := os.Create("./info.xml")
if err != nil {
fmt.Println("文件创建失败", err.Error())
return
}
defer f.Close()
encoder := xml.NewEncoder(f)
err = encoder.Encode(info)
if err != nil {
fmt.Println("编码错误:", err.Error())
return
} else {
fmt.Println("编码成功")
}
}
func read() {
file, err := os.Open("./info.xml")
if err != nil {
fmt.Printf("文件打开失败:%v", err)
return
}
defer file.Close()
info := Website{}
decoder := xml.NewDecoder(file)
err = decoder.Decode(&info)
if err != nil {
fmt.Printf("解码失败:%v", err)
return
} else {
fmt.Println("解码成功")
fmt.Println(info)
}
}
Gob
package main
import (
"encoding/gob"
"fmt"
"os"
)
func write() {
info := map[string]string{
"name": "Golang",
"website": "http://www.ibug.info/golang/",
}
name := "demo.gob"
File, _ := os.OpenFile(name, os.O_RDWR|os.O_CREATE, 0777)
defer File.Close()
enc := gob.NewEncoder(File)
if err := enc.Encode(info); err != nil {
fmt.Println(err)
}
}
func read() {
var M map[string]string
File, _ := os.Open("demo.gob")
D := gob.NewDecoder(File)
D.Decode(&M)
fmt.Println(M)
}
Txt
package main
import (
"bufio"
"fmt"
"os"
)
func write() {
filePath := "./output.txt"
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("打开文件错误= %v \n", err)
return
}
defer file.Close()
str := "http://www.ibug.info/golang/\n"
writer := bufio.NewWriter(file)
for i := 0; i < 3; i++ {
writer.WriteString(str)
}
writer.Flush()
}
func read() {
file, err := os.Open("./output.txt")
if err != nil {
fmt.Println("文件打开失败 = ", err)
}
defer file.Close()
reader := bufio.NewReader(file)
for {
str, err := reader.ReadString('\n')
if err == io.EOF {
break
}
fmt.Print(str)
}
fmt.Println("文件读取结束...")
}
Bin
package main
import (
"encoding/gob"
"fmt"
"os"
)
func write() {
info := "http://www.ibug.info/golang/"
file, err := os.Create("./output.gob")
if err != nil {
fmt.Println("文件创建失败", err.Error())
return
}
defer file.Close()
encoder := gob.NewEncoder(file)
err = encoder.Encode(info)
if err != nil {
fmt.Println("编码错误", err.Error())
return
} else {
fmt.Println("编码成功")
}
}
func read() {
file, err := os.Open("./output.gob")
if err != nil {
fmt.Println("文件打开失败", err.Error())
return
}
defer file.Close()
decoder := gob.NewDecoder(file)
info := ""
err = decoder.Decode(&info)
if err != nil {
fmt.Println("解码失败", err.Error())
} else {
fmt.Println("解码成功")
fmt.Println(info)
}
}
Zip
package main
import (
"archive/zip"
"bytes"
"fmt"
"os"
)
func write() {
buf := new(bytes.Buffer)
w := zip.NewWriter(buf)
var files = []struct {
Name, Body string
}{
{"Golang.txt", "http://www.ibug.info/golang/"},
}
for _, file := range files {
f, err := w.Create(file.Name)
if err != nil {
fmt.Println(err)
}
_, err = f.Write([]byte(file.Body))
if err != nil {
fmt.Println(err)
}
}
err := w.Close()
if err != nil {
fmt.Println(err)
}
f, err := os.OpenFile("file.zip", os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
fmt.Println(err)
}
buf.WriteTo(f)
}
func read() {
r, err := zip.OpenReader("file.zip")
if err != nil {
fmt.Printf(err.Error())
}
defer r.Close()
for _, f := range r.File {
fmt.Printf("文件名: %s\n", f.Name)
rc, err := f.Open()
if err != nil {
fmt.Printf(err.Error())
}
_, err = io.CopyN(os.Stdout, rc, int64(f.UncompressedSize64))
if err != nil {
fmt.Printf(err.Error())
}
rc.Close()
}
}
File Lock
package main
import (
"fmt"
"os"
"sync"
"syscall"
"time"
)
type FileLock struct {
dir string
f *os.File
}
func New(dir string) *FileLock {
return &FileLock{
dir: dir,
}
}
func (l *FileLock) Lock() error {
f, err := os.Open(l.dir)
if err != nil {
return err
}
l.f = f
err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if err != nil {
return fmt.Errorf("cannot flock directory %s - %s", l.dir, err)
}
return nil
}
func (l *FileLock) Unlock() error {
defer l.f.Close()
return syscall.Flock(int(l.f.Fd()), syscall.LOCK_UN)
}
func main() {
test_file_path, _ := os.Getwd()
locked_file := test_file_path
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func(num int) {
flock := New(locked_file)
err := flock.Lock()
if err != nil {
wg.Done()
fmt.Println(err.Error())
return
}
fmt.Printf("output : %d\n", num)
wg.Done()
}(i)
}
wg.Wait()
time.Sleep(2 * time.Second)
}