08 File operation and JSON format conversion

File operations

os.File encapsulates all file-related operations, File is a structure

Access the file
func Open (name string) (file *File ,err error) to
open a file for subsequent operations. If the operation is successful, the file object will be returned, otherwise it will return the exception message
fun (f *File) Close () error.
Close the file and make the file unavailable Errors may occur when reading, writing, and returning.

func OpenFile (name string, flag int, perm fileMode) (file *File, err error)
Open file function, use the specified option, the specified mode to open the specified file.
The flag values ​​are as follows:
Insert picture description here
fileMode parameter value: the same as linux file permission control, 0666 means read and write

func Copy (dst Writer, src Reader) (written int64, err error)
file copy

Read file code

func test01(){
    
    
	//打开文件
	file,err := os.Open("C:\\E\\goworks\\src\\go04\\file\\test01.txt")
	if err!= nil {
    
    
		fmt.Println("open file err",err)
		return
	}
	
	//fmt.Printf("file=v% \n",file)

	//读取文件内容
	reader := bufio.NewReader(file)
	for{
    
    
		str,err := reader.ReadString('\n')//读到一个换行就结束
		fmt.Println(str)
		if err == io.EOF{
    
    
			break
		}
		
	}

	err = file.Close()//关闭文件
	if err!= nil{
    
    
		fmt.Println("close file err",err)
		return 
	}
}

Write file code

//文件写入
func test02(){
    
    
	//打开文件
	filePath :="C:\\E\\goworks\\src\\go04\\file\\test02.txt"
	file,err := os.OpenFile(filePath,os.O_WRONLY|os.O_CREATE,0666)

	if err!= nil {
    
    
		fmt.Println("open file err",err)
		return
	}
	defer file.Close()
	
	//fmt.Printf("file=v% \n",file)

	//读取文件内容
	writer := bufio.NewWriter(file)
	for i:=0;i<5;i++{
    
    
		writer.WriteString("nihao\n")
	}
	//writer 是写缓存,因此写完后必须调用Flush 方法,将缓存数据持久化
	writer.Flush()
}

File copy

//文件复制
func CopyFile(dstFileName string,srcFileName string)(written int64,err error){
    
    
	srcFile,err:=os.Open(srcFileName)
	if(err != nil){
    
    
		fmt.Println("打开文件异常",err)
		return
	}
	//if()
	disFile,err:=os.OpenFile(dstFileName,os.O_WRONLY|os.O_CREATE,0666)
	if(err != nil){
    
    
		fmt.Println("打开文件异常",err)
		return
	}
	defer srcFile.Close()
	defer disFile.Close()
	reader := bufio.NewReader(srcFile)
	writer:=bufio.NewWriter(disFile)

	return io.Copy(writer,reader)

}

Does the file exist

//判断文件是否存在
func PathExists(path string)(bool,error){
    
    
	_,err := os.Stat(path)
	//如果os.Stat 方法未返回异常 则 表示目录存在
	if err==nil{
    
    
		return true,nil
	}
	//如果 返回了异常 判断 os.IsNotExist 返回true 
	//表示目录不存在
	
	if os.IsNotExist(err){
    
    
		return false,nil
	}
	//其他情况不确定是否存在
	return false,err
}

JSON format conversion

javascript Object notation is a lightweight data exchange format. It has become the main data format. The conversion between the json format string and the data structure is a language standard.

Serialization: Convert the qualified data structure into a JSON string.
Deserialization: Deserialization refers to the conversion of a JSON string into the corresponding data structure.
Note

  1. For the serialization of the structure, if we want to re-customize the name of the field after serialization, we can define the tag tag in the structure.
    Sample code
func test05(){
    
    
	mon :=Monster{
    
    
		Name:"牛魔王",
		Age:100,
		Skill:"必杀技",
	}
	//序列化
	data,_:=json.Marshal(&mon)
	//{"Name":"牛魔王","MonsterAge":100,"Skill":"必杀技"}
	fmt.Println(string(data))

	//反序列化
	var a Monster ;
	json.Unmarshal(data,&a) 
	fmt.Println("struct反序列化结果:",a)


	//map 序列化
	map1 := map[string] interface{
    
    }{
    
    
		"name":"tom",
		"age":18,
		"skill":"bisha",
	}

	data,_ =json.Marshal(map1)
	fmt.Println(string(data))//{"age":18,"name":"tom","skill":"bisha"}
	
	//反序列化
	var b map[string] interface{
    
    }
	json.Unmarshal(data,&b) 
	fmt.Println("map反序列化结果:",b)
	
	//切片序列化
	var sli []map[string]interface{
    
    } 
	var m1 map[string]interface{
    
    }
	m1 = make(map[string]interface{
    
    })
	m1["name"]="tom"
	m1["age"]=19
	m1["skill"]="haha"
	sli=append(sli,m1)

	data,_ = json.Marshal(sli)
	//[{"age":19,"name":"tom","skill":"haha"}]
	fmt.Println(string(data))
	//反序列化
	var c []map[string]interface{
    
    } 
	json.Unmarshal(data,&c) 
	fmt.Println("map反序列化结果:",c)

	//基本类型序列化
	data,_ = json.Marshal(18)
	fmt.Println(string(data))//18
}

Guess you like

Origin blog.csdn.net/zhangxm_qz/article/details/115262623