current position:Home>[golang] go into go language lesson 22 JSON & file reading and writing

[golang] go into go language lesson 22 JSON & file reading and writing

2021-08-25 18:49:43 I'm Xiaobai

【Golang】️ Walk into Go Language ️ Lesson 22 json & File read and write

summary

Golang Is a new cross platform programming language . Today, Xiaobai will take you hand in hand into Golang The world of . ( The first 22 course )

 Insert picture description here

json

json (JavaScript Object Notation) Is a lightweight data exchange format .

 Insert picture description here

code

Format :

json.Marshal(v interface{})

Example :

package main

import (
	"encoding/json"
	"fmt"
)

func main() {

	type person struct {
		Name string
		Job string
	}

	Bob := person{
		"Bob",
		" Excrement extractor ",
	}

	//  code 
	b, error := json.Marshal(Bob)

	if error != nil {
		fmt.Println(error)
	}

	//  Debug output 
	fmt.Println(b)
	fmt.Println(string(b))

}

Output results :

[123 34 78 97 109 101 34 58 34 66 111 98 34 44 34 74 111 98 34 58 34 230 142 143 231 178 170 229 183 165 34 125]
{"Name":"Bob","Job":" Excrement extractor "}

decode

package main

import (
	"encoding/json"
	"fmt"
)

func main() {

	type person struct {
		Name string
		Job string
	}

	//  convert to json
	var jsonbytes = []byte(`{"Name": "bob","Job": "dancer"}`)
	fmt.Println(jsonbytes)

	//  Defining variables p
	var p person
	
	//  decode 
	error := json.Unmarshal(jsonbytes, &p)
	if error != nil {
		fmt.Println(error)
	}
	
	//  Debug output 
	fmt.Printf("%+v", p)

}

Output results :

[123 34 78 97 109 101 34 58 32 34 98 111 98 34 44 34 74 111 98 34 58 32 34 100 97 110 99 101 114 34 125]
{Name:bob Job:dancer}

File read and write

File reading and writing is a common operation . Go Language provides support for a variety of text operations .

 Insert picture description here

File read

Format :

ReadAll(r io.Reader) ([]byte, error)

Read the entire file :

package main

import (
	"fmt"
	"io/ioutil"
	"os"
)

func main() {

	//  Open file 
	file, err := os.Open("C:/Users/Windows/Desktop/project2/read_write/read/1.txt")
	fmt.Println(file, err)
    
    //  Delay off 
    defer file.Close()

	//  Read entire file 
	read_bytes, err := ioutil.ReadAll(file)

	//  Debug output 
	fmt.Println(string(read_bytes))

}

Output results :

&{0xc0000da780} <nil>
A
B
C
D

Read file by byte (panic Used to throw an error ):

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {

	//  Open file 
	file, err := os.Open("C:/Users/Windows/Desktop/project2/read_write/read/1.txt")

	if err != nil {
		panic(err)
	}

	//  Delay off 
	defer file.Close()

	//  establish byte Arrays are used to hold data 
	result := make([]byte, 0)

	//  Create buffer 
	buffer := make([]byte, 1024)
	for {
		//  Read 1kb
		n, err := file.Read(buffer)

		//  Error handling 
		if err != nil && err != io.EOF {
			panic(err)
		}

		//  Out of the loop 
		if 0 == n {
			break
		}

		// append ( add ... You can append an array ,  Otherwise, you can only append elements )
		result = append(result, buffer[:n]...)
	}

	//  Debug output final result 
	fmt.Println(string(result))

}

write file

Format :

file.Write(f *File) Write(b []byte)

Return value :

  • nums: Number of bytes written
  • err: error

Example :

package main

import (
	"fmt"
	"os"
)

func main() {

	//  Define string ,  And convert it into a byte array 
	input := []byte("Hello World")

	//  Wear a file 
	file, err := os.Create("1.txt")

	if err != nil {
		panic(err)
	}

	//  Delay off 
	defer file.Close()

	//  write file 
	nums, err := file.Write(input)

	if err != nil {
		panic(err)
	}

	//  Number of bytes written to debug output 
	fmt.Println(" Number of bytes :", nums)

}

Output results :

 Number of bytes : 11

 Insert picture description here

copyright notice
author[I'm Xiaobai],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825184941016p.html

Random recommended