Sunday, 26 May 2019

Java: Print all the file names in a directory and sub directories


Approach 1: Depth First Search

App.java
package com.sample.app;

import java.io.File;

public class App {
  
  private static void printFileNames(File directory, String tab) {
    File[] files = directory.listFiles();
    for(File file: files) {
      if(file.isDirectory()) {
        System.out.println(tab + file.getName());
        printFileNames(file, tab + "  ");
      }else {
        System.out.println(tab + file.getName());
      }
    }
  }
  
  public static void printFileNames(File file) {
    if(!file.exists() || !file.isDirectory()) {
      System.out.println("file is not exits or not a directory");
    }
    printFileNames(file, "");
  }
  

  public static void main(String args[]) {

    File file = new File("/Users/krishna/Documents/TechnicalDocuments");
    
    printFileNames(file);
  }

}

Approach 2: Using Breadth First Search

FileSearch.java
package com.sample.app;

import java.io.File;
import java.util.LinkedList;
import java.util.Queue;

public class FileSearch {
  private Queue<File> queue;

  public FileSearch(String filePath) {
    File file = new File(filePath);
    if (!file.exists() || !file.isDirectory()) {
      System.out.println("file is not exits or not a directory");
    }

    queue = new LinkedList<File>();
    queue.add(file);
  }

  public void printFileNames() {

    printFiles();
  }

  private void printFiles() {

    do {
      File directory = queue.remove();

      File[] files = directory.listFiles();

      for (File tempFile : files) {
        if (tempFile.isDirectory()) {
          queue.add(tempFile);
        }
        System.out.println(tempFile.getName());
      }

    } while (!queue.isEmpty());

  }

}


App.java
package com.sample.app;

public class App {
  
  public static void main(String args[]) {

    FileSearch fileSearch = new FileSearch("/Users/krishna/Documents/TechnicalDocuments");
    
    fileSearch.printFileNames();
  }

}


You may like




No comments:

Post a Comment