1
go基础之读取ini
source link: https://blog.51cto.com/u_3764469/5606982
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
go基础之读取ini
精选 原创使用读文件方式提取ini文件内容
test.ini文件内容
[aa]
a1=11
a2=22
[bb]
b1=33
b2=44
a1=11
a2=22
[bb]
b1=33
b2=44
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println(readFileIni("bb", "b2"))
}
func readFileIni(master, detail string) string {
var result string = ""
file, err := os.Open("test.ini")
if err != nil {
fmt.Println(err)
}
defer file.Close()
var sectionName string
reader := bufio.NewScanner(file)
for reader.Scan() {
linestr := reader.Text()
strings.TrimSpace(linestr)
if linestr == "" {
continue
}
if linestr[0] == ';' {
continue
}
if string(linestr[0]) == "[" && string(linestr[len(linestr)-1]) == "]" {
sectionName = linestr[1 : len(linestr)-1]
} else if sectionName == master {
pair := strings.Split(linestr, "=")
if len(pair) == 2 {
key := strings.TrimSpace(pair[0])
if key == detail {
result = pair[1]
}
}
}
}
return result
}
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println(readFileIni("bb", "b2"))
}
func readFileIni(master, detail string) string {
var result string = ""
file, err := os.Open("test.ini")
if err != nil {
fmt.Println(err)
}
defer file.Close()
var sectionName string
reader := bufio.NewScanner(file)
for reader.Scan() {
linestr := reader.Text()
strings.TrimSpace(linestr)
if linestr == "" {
continue
}
if linestr[0] == ';' {
continue
}
if string(linestr[0]) == "[" && string(linestr[len(linestr)-1]) == "]" {
sectionName = linestr[1 : len(linestr)-1]
} else if sectionName == master {
pair := strings.Split(linestr, "=")
if len(pair) == 2 {
key := strings.TrimSpace(pair[0])
if key == detail {
result = pair[1]
}
}
}
}
return result
}
首先打开ini文件,然后对文件进行逐行读取,去掉每行的空格,注释,空行,以[开头以]结尾的数据截取出来赋予sectionName,如果需要获取的名字与sectionName相同就可以继续往下获取子配置,子配置主要就是根据=来进行分割key和value了。
- 赞
- 收藏
- 评论
- 分享
- 举报
上一篇:go基础之select
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK