package main import ( "fmt" "io/ioutil" "log" "os" "strings" ) func main() { files := ScanDir("employment") for _, file := range files { fmt.Println(file) //通过字符串截取获取到学校id schId := GetLastPathName(file) fmt.Println(schId) insides := ScanDirs(file) for _, inside := range insides { fmt.Println(inside) insidePath := GetLastPathName(inside) switch insidePath { //学校加专业 case "schMajorDetail": SetMajorSch(SchMajorDetail, inside) //同等院校加专业 case "similarSchMajorDetail": SetMajorSch(SimilarSchMajorDetail, inside) //学校详情 case "schDetail": //就业包装--学校详情页就业去向 GetFileContentByPath(inside) case "schOverview": GetFileContentByPath(inside) } fmt.Println(insidePath) //就业包装--学校详情页就业去向 "schOverview.json" } } } const SchMajorDetail = 1 const SimilarSchMajorDetail = 2 func SetMajorSch(typeNum int32, path string) { //递归获取当前文件夹下的所有文件 files := ScanDir(path) for _, file := range files { majorId := GetLastPathName(file) log.Println(majorId) //获取文件内容 GetFileContentByPath(file) //序列化 // todo } if SchMajorDetail == typeNum { } } //GetLastPathName 获取当前文件lastName func GetLastPathName(path string) string { array := strings.Split(path, "\\") if array != nil && len(array) > 0 { pathName := array[len(array)-1] pathName = strings.Replace(pathName, ".json", "", -1) return pathName } return "" } //GetFileContentByPath 根据 all path 获取文件内容 func GetFileContentByPath(path string) string { file, err := os.Open(path) if err != nil { fmt.Println(err) return "" } defer file.Close() fileinfo, err := file.Stat() if err != nil { fmt.Println(err) return "" } filesize := fileinfo.Size() buffer := make([]byte, filesize) bytesread, err := file.Read(buffer) if err != nil { fmt.Println(err) return "" } fmt.Println("bytes read: ", bytesread) return string(buffer) } //ScanDir 扫描当前目录下文件,不递归扫描 func ScanDir(dirName string) []string { files, err := ioutil.ReadDir(dirName) if err != nil { log.Println(err) } var fileList []string for _, file := range files { fileList = append(fileList, dirName+string(os.PathSeparator)+file.Name()) } return fileList } //ScanDirs 递归扫描目录 func ScanDirs(dirName string) []string { files, err := ioutil.ReadDir(dirName) if err != nil { log.Println(err) } var fileList []string for _, file := range files { fileList = append(fileList, dirName+string(os.PathSeparator)+file.Name()) if file.IsDir() { fileList = append(fileList, ScanDir(dirName+string(os.PathSeparator)+file.Name())...) } } return fileList }
目录示例