java如何获取一个目录的深度呢?
下文笔者讲述java代码获取目录深度的方法及示例分享,如下所示
获取目录深度的实现思路
通过递归的方式,依次遍历获取一个目录信息 即可得到一个目录的深度例:获取目录深度的示例
import java.io.File; public class DirectoryDepth { public static void main(String[] args) { // 测试目录路径 String path = "/test/dirs"; File directory = new File(path); int depth = getDepth(directory); System.out.println("目录 " + path + " 的深度为 " + depth); } // 获取目录深度 public static int getDepth(File directory) { int depth = 0; if (directory.isDirectory()) { File[] files = directory.listFiles(); // 如果目录为空,深度为1 if (files == null || files.length == 0) { return 1; } for (File file : files) { // 递归获取子目录的深度 if (file.isDirectory()) { depth = Math.max(depth, getDepth(file)); } } // 当前目录深度 = 子目录最大深度 + 1 depth += 1; } return depth; } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。