📌  相关文章
📜  Java程序列出目录和嵌套子目录中的所有文件

📅  最后修改于: 2022-05-13 01:55:19.446000             🧑  作者: Mango

Java程序列出目录和嵌套子目录中的所有文件

先决条件:文件类

给定一个主目录/文件夹,列出其中的所有文件,如果该目录有其他嵌套的子目录,则列出其中的文件。在上述问题中很容易观察到一个简单的递归模式。

算法 :

  1. 为主目录创建一个 File 对象。
  2. 获取主目录的文件数组。
  3. 如果 array[i] 是一个文件:
    • 打印出文件名。
  4. 如果 array[i] 是一个目录:
    • 打印出目录名称。
    • 获取当前子目录的文件数组。
    • 对当前子目录重复步骤 3 和 4。
  5. 对下一个数组 [i] 重复步骤 3 和 4。

示例 1:

Java
// Java program to print all files
// in a folder(and sub-folders)
 
import java.io.File;
 
public class GFG {
    static void RecursivePrint(File[] arr, int index, int level)
    {
        // terminate condition
        if (index == arr.length)
            return;
 
        // tabs for internal levels
        for (int i = 0; i < level; i++)
            System.out.print("\t");
 
        // for files
        if (arr[index].isFile())
            System.out.println(arr[index].getName());
 
        // for sub-directories
        else if (arr[index].isDirectory()) {
            System.out.println("[" + arr[index].getName()
                               + "]");
 
            // recursion for sub-directories
            RecursivePrint(arr[index].listFiles(), 0,
                           level + 1);
        }
 
        // recursion for main directory
        RecursivePrint(arr, ++index, level);
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        // Provide full path for directory(change
        // accordingly)
        String maindirpath
            = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
 
        // File object
        File maindir = new File(maindirpath);
 
        if (maindir.exists() && maindir.isDirectory()) {
             
              // array for files and sub-directories
            // of directory pointed by maindir
            File arr[] = maindir.listFiles();
 
            System.out.println(
                "**********************************************");
            System.out.println(
                "Files from main directory : " + maindir);
            System.out.println(
                "**********************************************");
 
            // Calling recursive method
            RecursivePrint(arr, 0, 0);
        }
    }
}


Java
// Recursive Java program to print all files
// in a folder(and sub-folders)
 
import java.io.File;
 
public class GFG {
    static void RecursivePrint(File[] arr, int level)
    {
        // for-each loop for main directory files
        for (File f : arr) {
            // tabs for internal levels
            for (int i = 0; i < level; i++)
                System.out.print("\t");
 
            if (f.isFile())
                System.out.println(f.getName());
 
            else if (f.isDirectory()) {
                System.out.println("[" + f.getName() + "]");
 
                // recursion for sub-directories
                RecursivePrint(f.listFiles(), level + 1);
            }
        }
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        // Provide full path for directory(change
        // accordingly)
        String maindirpath
            = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
 
        // File object
        File maindir = new File(maindirpath);
 
        if (maindir.exists() && maindir.isDirectory()) {
            // array for files and sub-directories
            // of directory pointed by maindir
            File arr[] = maindir.listFiles();
 
            System.out.println(
                "**********************************************");
            System.out.println(
                "Files from main directory : " + maindir);
            System.out.println(
                "**********************************************");
 
            // Calling recursive method
            RecursivePrint(arr, 0);
        }
    }
}


Java
// Iterative Program to get all file names in Directory and
// SubDirectory
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // provide complete path for directory(to be changed
        // accordingly)
        String mainDir = "c:\\GFG\\example";
        // File object
        File file = new File(mainDir);
        Stack s = new Stack<>();
        s.push(file);
        // initially stack is not empty
        System.out.println("Content of Directory " + mainDir
                           + " is");
        while (!s.empty()) {
            File tmpF = s.pop();
            // check if it is a file or not
            if (tmpF.isFile()) {
                // print file name can code here according
                // to our need
                System.out.println(tmpF.getName());
            }
            else if (tmpF.isDirectory()) {
                // It's an directory hence list and push all
                // files in stack
                File[] f = tmpF.listFiles();
                for (File fpp : f) {
                    s.push(fpp);
                }
            } // else if ends here
        } // stack is not empty loop ends here
    } // main function ends here
}



输出:

**********************************************
Files from main directory : C:\Users\Gaurav Miglani\Desktop\Test
**********************************************
Cormen.pdf
Extra-Items.pdf
XYZ.pdf
[Docs]
    A.docx
    B.doc
    C.docx
ABC.pdf
JKL.pdf
[sheets]
    XXX.csv
    YYY.csv
results.pdf
[Resumes]
    [Before2016]
        Resume2015.doc
        Resume2016.doc
        [Before2014]
            Resume2014.doc
    Resume2017.doc
    Resume2017.pdf
        QA.doc
Testing.pdf

示例 2:下面是另一个递归程序。这里我们只对嵌套的子目录使用递归。对于主目录文件,我们使用 foreach 循环。

Java

// Recursive Java program to print all files
// in a folder(and sub-folders)
 
import java.io.File;
 
public class GFG {
    static void RecursivePrint(File[] arr, int level)
    {
        // for-each loop for main directory files
        for (File f : arr) {
            // tabs for internal levels
            for (int i = 0; i < level; i++)
                System.out.print("\t");
 
            if (f.isFile())
                System.out.println(f.getName());
 
            else if (f.isDirectory()) {
                System.out.println("[" + f.getName() + "]");
 
                // recursion for sub-directories
                RecursivePrint(f.listFiles(), level + 1);
            }
        }
    }
 
    // Driver Method
    public static void main(String[] args)
    {
        // Provide full path for directory(change
        // accordingly)
        String maindirpath
            = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
 
        // File object
        File maindir = new File(maindirpath);
 
        if (maindir.exists() && maindir.isDirectory()) {
            // array for files and sub-directories
            // of directory pointed by maindir
            File arr[] = maindir.listFiles();
 
            System.out.println(
                "**********************************************");
            System.out.println(
                "Files from main directory : " + maindir);
            System.out.println(
                "**********************************************");
 
            // Calling recursive method
            RecursivePrint(arr, 0);
        }
    }
}


输出:

**********************************************
Files from main directory : C:\Users\Gaurav Miglani\Desktop\Test
**********************************************
Cormen.pdf
Extra-Items.pdf
XYZ.pdf
[Docs]
    A.docx
    B.doc
    C.docx
ABC.pdf
JKL.pdf
[sheets]
    XXX.csv
    YYY.csv
results.pdf
[Resumes]
    [Before2016]
        Resume2015.doc
        Resume2016.doc
        [Before2014]
            Resume2014.doc
    Resume2017.doc
    Resume2017.pdf
        QA.doc
Testing.pdf

示例 3 –

下面是另一个使用 Stack DS 获取所有文件名的迭代程序

Java

// Iterative Program to get all file names in Directory and
// SubDirectory
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // provide complete path for directory(to be changed
        // accordingly)
        String mainDir = "c:\\GFG\\example";
        // File object
        File file = new File(mainDir);
        Stack s = new Stack<>();
        s.push(file);
        // initially stack is not empty
        System.out.println("Content of Directory " + mainDir
                           + " is");
        while (!s.empty()) {
            File tmpF = s.pop();
            // check if it is a file or not
            if (tmpF.isFile()) {
                // print file name can code here according
                // to our need
                System.out.println(tmpF.getName());
            }
            else if (tmpF.isDirectory()) {
                // It's an directory hence list and push all
                // files in stack
                File[] f = tmpF.listFiles();
                for (File fpp : f) {
                    s.push(fpp);
                }
            } // else if ends here
        } // stack is not empty loop ends here
    } // main function ends here
}

输出:

Content of Directory c:\GFG\example is
example.txt
testTwo.java
testTwo.class
test.java
test.class
test.java
eg1.java
eg1.class
test.java
test.class
Students.java
Students.class