递归遍历目录的缺点:遇到多层级目录时,层级越多,堆栈的负荷越大。
[java] view
plaincopyprint?
- import java.io.File;
- import java.util.LinkedList;
- /*
- * 采用非递归方式遍历目录及其子目录的文件
- */
- public class ProcessDirectory {
- public static int num;//文件总量
- public static void main(String[] args) {
- String path = "/Users/Jackie/Downloads/temp";
- // scanDirNoRecursion(path);
- scanDirRecursion(new File(path));
- System.out.println(path + "目录下共有文件数量为:" + num);
- }
- // 非递归
- public static void scanDirNoRecursion(String path) {
- LinkedList list = new LinkedList();
- File file = new File(path);
- if (file.isFile()) {
- System.out.println(file.getAbsolutePath());
- num++;
- return;
- }
- list.add(file); //是目录则添加进链表
- while (!list.isEmpty()) { //如果不为空
- File f = (File) list.removeFirst(); //先进先出,取出首个文件目录对象并且移除
- File[] listFiles = f.listFiles();
- if (listFiles == null) {
- return;
- }
- int length
= listFiles.length; - for (int i = 0; i < length; i++) {
- if (listFiles[i].isDirectory()) {
- list.add(listFiles[i]);
- } else {
- System.out.println(listFiles[i].getAbsolutePath());
- num++;
- }
- }
- }
- System.out.println(path + "目录下共有文件数量为:" + num);
- }
- //递归
- public static void scanDirRecursion(File file) {
- if (file.isFile()) {
- System.out.println(file.getAbsolutePath());
- num++;
- return;
- }
- File[] listFiles = file.listFiles();
- int length
= listFiles.length; - for (int i = 0; i < length; i++) {
- scanDirRecursion(listFiles[i]);
- }
- }
- }
时间: 2024-11-13 22:47:59