使用Java递归遍历一个目录下的所有文件

mac2025-12-31  2

/** * 递归遍历目录下的所有文件 * @param path 扫描路径 */ public static void scanFile(String path){ File scanPath = new File(path); File[] fileList = null; //1.扫描路径若为目录,则将该目录下的所有文件(目录+文件)放入数组 //2.扫描路径若为文件,将该文件放入数组,该数组中就该文件一个元素 if(scanPath.isDirectory()){ fileList = scanPath.listFiles(); }else if(scanPath.isFile()){ fileList = new File[]{scanPath}; } //遍历数组 for (int i = 0; i < fileList.length; i++) { File file = fileList[i]; if(file.isDirectory()){ scanFile(file.getPath());//递归调用 }else if(file.isFile()){ System.out.println(file.getName()); } } }
最新回复(0)