To list sub directories recursively in a given directory


 / Published in: Java
 

  1. import java.io.File;
  2. import java.util.ArrayList;
  3. import java.util.Iterator;
  4. import java.util.List;
  5.  
  6. /**
  7.  *
  8.  */
  9.  
  10. /**
  11.  * @author hariharan_kumar
  12.  *
  13.  */
  14. public class Dfs {
  15.  
  16. List<String> directoryLists;
  17. /**
  18. *
  19. */
  20. public Dfs() {
  21.  
  22. directoryLists = new ArrayList<String>();
  23.  
  24. }
  25.  
  26. /**
  27. * @param args
  28. */
  29. public static void main(String[] args) {
  30.  
  31. Dfs df = new Dfs();
  32. df.iterate("G:/jbossTest");
  33. df.displayDirList();
  34.  
  35. }
  36.  
  37. public void iterate(String baseDir)
  38. {
  39. File folder_and_files = new File(baseDir);
  40. File[] file_array = folder_and_files.listFiles();
  41.  
  42. for(int i = 0;i < file_array.length;i++)
  43. {
  44. if(file_array[i].isDirectory())
  45. {
  46. //System.out.println("Directory is : " + file_array[i].getName());
  47. directoryLists.add(file_array[i].getAbsolutePath());
  48. iterate(file_array[i].getAbsolutePath());
  49. }
  50. else if (file_array[i].isFile())
  51. {
  52. //System.out.println("File is : " + file_array[i].getAbsolutePath());
  53.  
  54. }
  55. else if(file_array.length == i)
  56. {
  57. return;
  58. }
  59.  
  60. }
  61. }
  62.  
  63. public void displayDirList()
  64. {
  65. Iterator<String> i = directoryLists.iterator();
  66. while(i.hasNext())
  67. {
  68. System.out.println(i.next());
  69. }
  70. }
  71. }

Report this snippet  

You need to login to post a comment.