Golang 07 读写数据

总篇:34

编辑于 2025/6/24 14:00

截稿于: 2025/6/24 23:00

《Go 入门指南》 | Go 技术论坛

第十二章

读取输入

回顾Java:

Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
Go的输入更像C,采用Scanf("%s %s",&a,&b):
package main

import "fmt"

func main() {
	input1()
}

func input1() {
	var (
		firstName, lastName string
	)
    // 一般采用这一种方式,格式化输入:
	fmt.Println("输入全名: ")
	fmt.Scanf("%s %s", &firstName, &lastName)
	fmt.Printf("Hi %s %s!\n", firstName, lastName)
    // 这种以空格分开
    // fmt.Println("输入全名: ")
	// fmt.Scanln(&firstName, &lastName)
	// fmt.Printf("Hi %s %s!\n", firstName, lastName)
}

另外还有读取一行:

func input2() {
	var inputReader *bufio.Reader
	var input string
	var err error
	inputReader = bufio.NewReader(os.Stdin)
	fmt.Println("Please enter some input: ")
	input, err = inputReader.ReadString('\n')
	if err == nil {
		fmt.Printf("The input was: %s\n", input)
	}
}

读写文件

读取文件

一行一行读取:

package main

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

func main() {
	file1()
}


func file1() {
	inputFile, inputError := os.Open("input.txt")
	if inputError != nil {
		fmt.Printf("An error occurred on opening the inputfile\n" +
			"Does the file exist?\n" +
			"Have you got acces to it?\n")
		return // exit the function on error
	}
	defer inputFile.Close()

	inputReader := bufio.NewReader(inputFile)
	for {
		inputString, readerError := inputReader.ReadString('\n')
		fmt.Print(inputString)
		if readerError == io.EOF {
			return
		}
	}
}

一次读取整个文件:
package main

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

func main() {
	file2()
}
func file2() {
	inputFile := "input.txt"
	outputFile := "output.txt"
	buf, err := os.ReadFile(inputFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
		return
	}
	fmt.Printf("%s\n", string(buf))
	err = os.WriteFile(outputFile, buf, 0644)
	if err != nil {
		fmt.Fprintf(os.Stderr, "File Error: %s\n", err)
		return
	}
}

写文件:

package main

import (
    "os"
    "bufio"
    "fmt"
)

func main () {
    // var outputWriter *bufio.Writer
    // var outputFile *os.File
    // var outputError os.Error
    // var outputString string
    outputFile, outputError := os.OpenFile("output.txt", os.O_WRONLY|os.O_CREATE, 0666)
    if outputError != nil {
        fmt.Printf("An error occurred with file opening or creation\n")
        return  
    }
    defer outputFile.Close()

    outputWriter := bufio.NewWriter(outputFile)
    outputString := "hello world!\n"

    for i:=0; i<10; i++ {
        outputWriter.WriteString(outputString)
    }
    outputWriter.Flush()
}
package main

import "os"

func main() {
    os.Stdout.WriteString("hello, world\n")
    f, _ := os.OpenFile("test", os.O_CREATE|os.O_WRONLY, 0)
    defer f.Close()
    f.WriteString("hello, world in a file\n")
}
  • os.O_RDONLY:只读
  • os.O_WRONLY:只写
  • os.O_CREATE:创建:如果指定文件不存在,就创建该文件。
  • os.O_TRUNC:截断:如果指定文件已存在,就将该文件的长度截为 0。

文件拷贝

io.copy

package main

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

func main() {
    CopyFile("target.txt", "source.txt")
    fmt.Println("Copy done!")
}

func CopyFile(dstName, srcName string) (written int64, err error) {
    src, err := os.Open(srcName)
    if err != nil {
        return
    }
    defer src.Close()

    dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
    if err != nil {
        return
    }
    defer dst.Close()
    return io.Copy(dst, src)
}

Struct数据转JSON格式

需要手动实体转json

 js, _ := json.Marshal(vc) //struct实例转为json格式
//将json格式数据转存为json文件
file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0666)
    defer file.Close()
    enc := json.NewEncoder(file)
    err := enc.Encode(vc)
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)

type Address struct {
    Type    string
    City    string
    Country string
}

type VCard struct {
    FirstName string
    LastName  string
    Addresses []*Address
    Remark    string
}

func main() {
    pa := &Address{"private", "Aartselaar", "Belgium"}
    wa := &Address{"work", "Boom", "Belgium"}
    vc := VCard{"Jan", "Kersschot", []*Address{pa, wa}, "none"}
    // fmt.Printf("%v: \n", vc) // {Jan Kersschot [0x126d2b80 0x126d2be0] none}:
    // JSON format:
    js, _ := json.Marshal(vc)
    fmt.Printf("JSON format: %s", js)
    // using an encoder:
    file, _ := os.OpenFile("vcard.json", os.O_CREATE|os.O_WRONLY, 0666)
    defer file.Close()
    enc := json.NewEncoder(file)
    err := enc.Encode(vc)
    if err != nil {
        log.Println("Error in encoding json")
    }
}

读取json文件转为struct:
package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)

type Address struct {
    Type    string
    City    string
    Country string
}

type VCard struct {
    FirstName string
    LastName  string
    Addresses []*Address
    Remark    string
}

func main() {
   	// 打开 JSON 文件
	file, err := os.Open("vcard.json")
	if err != nil {
		log.Fatalf("File error: %s\n", err)
	}
	defer file.Close()

	// 创建 JSON 解码器
	decoder := json.NewDecoder(file)

	// 定义结构体变量
	var vc VCard

	// 解析 JSON 数据
	err = decoder.Decode(&vc)
	if err != nil {
		log.Fatalf("JSON error: %s\n", err)
	}

	// 打印解析后的结构体
	fmt.Printf("VCard: %+v\n", vc)
}

posted on 2025-07-14 00:27  依只  阅读(9)  评论(0)    收藏  举报

导航