filename.json
===============
{
"filename":"NAV20130104",
"path":"F:\\golang\\test\\src\\photoweb"
}
NAV20130104 (以下只有二行,显示出来会有4行)
================
012013111502普通基金 03000111112500896637721111253255355718000000000222987522222222222222223333333330044444442222222222222222
022013111511普通基金(11000100017322428727400000157019839806000000000011032000000000000000000000000000000000000000000000000000
// 这里 要注意 make(map[string]interface{}, len(b)) 使用了空接口,可以存放任意类型
package mainimport (
"bufio"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math"
"os"
"strconv"
)
type rule struct {
itemname string //字段名
datatype string // 类型
length int // 长度
tail int // 小数点位数
chinesename string // 中文名字
}
var FdMap = map[string]string{} // {}为初始化成空
func readFile(filename string) (map[string]string, error) {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println("ReadFile: ", err.Error())
return nil, err
}
if err := json.Unmarshal(bytes, &FdMap); err != nil {
fmt.Println("Unmarshal: ", err.Error())
return nil, err
}
return FdMap, nil
}
func main() {
b := []rule{
{"l_serialno", "C", 2, 0, "序号"},
{"c_date", "C", 8, 0, "日期"},
{"c_fundname", "C", 12, 0, "基金名称"},
{"c_fundcode", "C", 6, 0, "基金代码"},
{"f_totalnetvalue", "F", 16, 2, "基金总净值"},
{"f_totalshares", "F", 16, 2, "基金总份额"},
{"f_netvalue", "F", 16, 4, "基金单位净值"},
{"f_income", "F", 16, 2, "基金收益"},
{"f_WFincome", "F", 9, 4, "万份基金收益"},
{"f_yearincome", "F", 9, 4, "年收益率"},
{"f_salefare", "F", 16, 2, "销售服务费"},
}
//读取配置文件
FdMap, err := readFile("./etc/filename.json")
if err != nil {
fmt.Println("readFile: ", err.Error())
return
}
//获取文件名
path, ok := FdMap["path"]
if !ok {
fmt.Println("解析失败!")
return
}
filename, ok := FdMap["filename"]
if !ok {
fmt.Println("解析失败!")
return
}
f, err := os.Open(path + "\\" + filename) //打开文件
//打开文件出错处理
defer f.Close()
if nil == err {
buff := bufio.NewReader(f) //读入缓存
for {
line, err := buff.ReadString('\n') //以'\n'为结束符读入一行
if err != nil || io.EOF == err {
break
}
for i, index := 0, 0; i < len(b); i++ {
if b[i].datatype == "F" {
tmp, err := strconv.ParseFloat(line[index:index+b[i].length], 10)
if err != nil {
fmt.Println("转换失败")
return
}
item[b[i].itemname] = tmp / math.Pow(10, float64(b[i].tail))
} else {
item[b[i].itemname] = line[index : index+b[i].length]
}
index += b[i].length
}
fmt.Println(item["c_fundcode"])
fmt.Printf("%16.2f\n", item["f_totalnetvalue"])
//把取到的值插入数据库
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
有疑问加站长微信联系(非本文作者)