将文件中的键值对(去空格)转化为map使用
例:配置文件application.properties
host= 127.0.0.1
port=8080
database=mysql
username=admin
passwd=123456
代码
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
var properties = make(map[string]string)
func init() {
srcFile, err := os.OpenFile("./application.properties", os.O_RDONLY, 0666)
defer srcFile.Close()
if err != nil {
fmt.Println("The file not exits.")
} else {
srcReader := bufio.NewReader(srcFile)
for {
str, err := srcReader.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
}
if 0 == len(str) || str == "\n" {
continue
}
properties[strings.Replace(strings.Split(str, "=")[0], " ", "", -1)] = strings.Replace(strings.Split(str, "=")[1], " ", "", -1)
}
}
}
func main() {
fmt.Print(properties["host"])
}
网友评论