Java-программа для вывода списка всех файлов в каталоге и вложенных подкаталогах
Предварительные требования: класс файла
Учитывая основной каталог/папку, перечислите все файлы из него, и если в этом каталоге есть другие вложенные подкаталоги, перечислите файлы из них. Довольно легко наблюдать простой шаблон рекурсии в приведенной выше задаче.
Алгоритм:
- Создайте объект File для основного каталога.
- Получить массив файлов для основного каталога.
- Если массив[i] является файлом:
- Распечатайте имя файла.
- Если массив[i] является каталогом:
- Распечатайте имя каталога.
- Получить массив файлов для текущего подкаталога.
- Повторите шаги 3 и 4 с текущим подкаталогом.
- Повторите шаги 3 и 4 со следующим массивом [i].
Пример 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( " " ); // 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 ); } } } |
Выход:
********************************************** Files from main directory : C:UsersGaurav MiglaniDesktopTest ********************************************** 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( " " ); 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:UsersGaurav MiglaniDesktopTest ********************************************** 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<File> 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:GFGexample 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
NOTE: The above code won’t compile on online IDE to compile and execute it download in your local system.
Эта статья предоставлена Гауравом Миглани . Если вам нравится GeeksforGeeks и вы хотите внести свой вклад, вы можете написать статью с помощью write.geeksforgeeks.org или отправить ее по адресу review-team@geeksforgeeks.org. Посмотрите, как ваша статья появится на главной странице GeeksforGeeks, и помогите другим гикам. Пожалуйста, пишите комментарии, если вы обнаружите что-то неправильное или хотите поделиться дополнительной информацией по теме, обсуждаемой выше.