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 }
目錄示例