banner
音小董

哩哔哩哔

这世上的热闹出自孤单

Chapter 7: File Reading and Writing and JSON Serialization

File Operations#

Reading a Single Line File#

package main  
  
import (  
"fmt"  
"os"  
)  
  
func main() {  
// Call the Open function under os to open the file  
file, err := os.Open("ReadWriteFile/a.txt")  
if err != nil {  
fmt.Println("File open error")  
return  
}  
// Close the resource, this line will actually run last  
defer file.Close()  
// Create a slice content, make([]byte, 100, 100) can be simplified to make([]byte, 100)  
content := make([]byte, 100)  
// Call the Read function to read the file and return the number of bytes the file occupies  
n, err := file.Read(content)  
if err != nil {  
fmt.Println("File read error")  
return  
}  
// Print the first n bytes and force it to be converted to a string  
fmt.Println(string(content[0:n]))  
}

Reading a Multi-line File#

package main  
  
import (  
"bufio"  
"fmt"  
"io"  
"os"  
)  
  
func main() {  
open, err := os.Open("ReadWriteFile/c.txt")  
if err != nil {  
fmt.Println("Read file error")  
return  
}  
defer open.Close()  
// Buffered reading  
reader := bufio.NewReader(open)  
for {  
// Pause reading a single line of content by line break, and then use a for loop to the last line  
readString, err := reader.ReadString('\n')  
if err != nil {  
// Trigger an error, io.EOF means reading the last line  
if err == io.EOF {  
// Print the content of the last line and end the loop  
fmt.Print(readString)  
break  
} else {  
fmt.Println("Error occurred:", err)  
return  
}  
} else {  
// Print each line of content except the last line  
fmt.Print(readString)  
}  
}  
}

Writing to a File#

package main  
  
import (  
"fmt"  
"os"  
)  
  
func main() {  
// Call the Create function under os to create a file  
file, err := os.Create("ReadWriteFile/c.txt")  
if err != nil {  
fmt.Println("Failed to create file")  
return  
}  
defer file.Close()  
content := "Hello, beautiful!"  
// Call the Write function to write to the file and return the number of bytes the file occupies  
n, err := file.Write([]byte(content))  
if err != nil {  
fmt.Println("Failed to write to file")  
return  
} else {  
fmt.Printf("Wrote %d bytes", n)  
}  
}

JSON Serialization#

package main  
  
import (  
"encoding/json"  
"fmt"  
)  
  
type Student struct {  
Name string  
Sex string  
Age int  
}  
  
type Class struct {  
Id string  
Students []Student  
}  
  
func main() {  
s := Student{"John Doe", "Male", 18}  
c := Class{"3rd Year, Class 2", []Student{s, s, s}}  
// Call the Marshal function to serialize  
m, err := json.Marshal(c)  
if err != nil {  
fmt.Println("JSON serialization failed", err)  
return  
}  
fmt.Println(string(m))  
println("_______________________________________________")  
// Call the Unmarshal function to deserialize  
var x Class  
err = json.Unmarshal(m, &x)  
if err != nil {  
fmt.Println("JSON deserialization failed", err)  
return  
}  
fmt.Println(x)  
}

Optimizing with a third-party library:

Import the package first, enter go get github.com/bytedance/sonic in the command terminal

package main  
  
import (  
"fmt"  
"github.com/bytedance/sonic"  
)  
  
type Student struct {  
Name string  
Sex string  
Age int  
}  
  
type Class struct {  
Id string  
Students []Student  
}  
  
func main() {  
s := Student{"John Doe", "Male", 18}  
c := Class{"3rd Year, Class 2", []Student{s, s, s}}  
// Use sonic instead of json, call the Marshal function to serialize  
m, err := sonic.Marshal(c)  
if err != nil {  
fmt.Println("JSON serialization failed", err)  
return  
}  
fmt.Println(string(m))  
println("_______________________________________________")  
// Use sonic instead of json, call the Unmarshal function to deserialize  
var x Class  
err = sonic.Unmarshal(m, &x)  
if err != nil {  
fmt.Println("JSON deserialization failed", err)  
return  
}  
fmt.Println(x)  
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.