Tuesday 3 October 2017

Print all the file names recursively

java.io.File class provides listFiles() method to get all the files presented in a directory. Below application uses listFiles() method and print all the file names in a directory.

FileUtil.java
import java.io.File;

public class FileUtil {

 /**
  * It print all the file names in a directory. if dirPath is null (or) empty
  * (or) not pointing to a directory, it prints nothing.
  * 
  * @param dirPath
  */
 public static void printFileNames(String dirPath) {
  if (dirPath == null || dirPath.isEmpty()) {
   return;
  }

  File file = new File(dirPath);
  if (!file.exists()) {
   return;
  }

  printAllFileNames(dirPath);

 }

 private static void printAllFileNames(String dirPath) {
  File file = new File(dirPath);
  File[] listOfFiles = file.listFiles();

  for (File tempFile : listOfFiles) {
   if (tempFile.isDirectory()) {
    printAllFileNames(tempFile.getAbsolutePath());
   } else {
    System.out.println(tempFile.getName());
   }
  }

 }
}


No comments:

Post a Comment