• go递归遍历文件目录


    package main
    
    import (
    	"fmt"
    	"io/ioutil"
    	"log"
    )
    
    //文件目录树形结构节点
    type dirTreeNode struct {
    	name  string
    	child []dirTreeNode
    }
    
    //递归遍历文件目录
    func getDirTree(pathName string) (dirTreeNode, error) {
    	rd, err := ioutil.ReadDir(pathName)
    	if err != nil {
    		log.Fatalf("Read dir '%s' failed: %v", pathName, err)
    	}
    	var tree, childNode dirTreeNode
    	tree.name = pathName
    	var name, fullName string
    	for _, fileDir := range rd {
    		name = fileDir.Name()
    		fullName = pathName + "/" + name
    		if fileDir.IsDir() {
    			childNode, err = getDirTree(fullName)
    			if err != nil {
    				log.Fatalf("Read dir '%s' failed: %v", fullName, err)
    			}
    		} else {
    			childNode.name = name
    			childNode.child = nil
    		}
    		tree.child = append(tree.child, childNode)
    	}
    	return tree, nil
    }
    
    //递归打印文件目录
    func printDirTree(tree dirTreeNode, prefix string) {
    	fmt.Println(prefix + tree.name)
    	if len(tree.child) > 0 {
    		prefix += "----"
    		for _, childNode := range tree.child {
    			printDirTree(childNode, prefix)
    		}
    	}
    }
    
    func main() {
    	dirName := "D:/go/src/jet"
    	tree, err := getDirTree(dirName)
    	if err != nil {
    		log.Fatalln("read dir '%s' fail: %v", dirName, err)
    	}
    	printDirTree(tree, "")
    }
    

      

  • 相关阅读:
    springboot springcloud zuul 过滤器
    springboot springcloud eureka 熔断器
    javaweb servlet filter
    maven nexus 搭建私服(二)
    springboot springcloud zuul 网关入门
    springboot springcloud 配置中心
    springboot springcloud eureka 入门
    java rabbitmq
    java jvm调优
    maven nexus 搭建私服(一)
  • 原文地址:https://www.cnblogs.com/wujuntian/p/11635879.html
Copyright © 2020-2023  润新知