Monday, 2 March 2015

How to List the contents / sub files of a directory in Java?


Even though, it looks a bit difficult, it's a simple interview question. If you observe the quesion carefully, the problem here is you need to print the contents of a dirctory to the console.
In any operating system, a directory consists of files such as text files, zip files, images, videos, or can contain another directory inside it.

To solve the problem, lets go through the solution,

1. First of all, consider a simple directory which consists of some files and one more directory inside it. for example "C:\Users\A8020\Desktop\Test". It consists of 5 pdf files and 1 sub directory. All you need to do is print the contents names to console.


2. In order to get the read access to the specified directory, you need to make use of File class. In object oriented languages such as Java, Scala, a class represents a real world object. Here the class "File" represents a file in the drive, and the file can be a directory, text file or any other.
3. So create an object of type File and pass the directory path to it's constructor , like below
File file = new File("C:/Users/A8020/Desktop/Test");

4. Now you got access to the directory. Next thing is, by using the object of File class, you need to get the contents inside the directory. for this, call listFiles() method on File's object.
file.listFiles();

The listFiles() method returns an array of objects of type File. So store them in an array.
File[] files = file.listFiles();

5. Now iterate the array using either simple for loop or enhanced for loop as below
Using simple for looop
  for(int i = 0; i < files.length; i++) {

   System.out.println("File "+i+": "+ files[i].getName());

  }
  
Using enhanced for loop
  for(File aFile : Files) {

   System.out.println("File " + aFile.getName());

  }
 

Listing all the files including subdirecory files :

1. The above code lists the files from the given direcoty but it won't list the files inside the subdirectory of a given directory.
2. For this, you need to change the code a bit.
3. While iterating the list of files inside the directory, you need to check whether the current file is a directory or not. If it is a directory, call the same method again, else display the file name in the console.
4. Here, we are using recursion to solve our problem.
5. recursion is a method that calls itself. If you look at the below method, you can get a clear idea.
 private void listAllFiles(File file) {

  File[] files = file.listFiles();

  for(File aFile : files) {

   if(aFile.isDirectory()) {

    System.out.println("Directory: " + aFile.getName());

    listAllFiles(aFile);

   } else {

    System.out.println("File: " + aFile.getName());

   }

  }  

 }

If you see here, we are calling listAllFiles(aFile) method again, from the same method ( listAllFiles(file)).

6. The above method will list all the files from the current direcory and as well as from the sub direcories.

7. The entire program is
  
package com.speakingcs.files;

import java.io.File;

public class FileTraversor {

 public static void main(String[] args) {

  FileTraversor ft = new FileTraversor();

  ft.listFiles(new File("C:/Users/A8020/Desktop/Test"));  

  ft.listAllFiles(new File("C:/Users/A8020/Desktop/contractDelta")); 

 } 

 private void listFiles(File file) {

  File[] files = file.listFiles();
  for(int i = 0; i < files.length; i++) {

   System.out.println("File " + i + ": " + files[i].getName());

  }

 }

 private void listAllFiles(File file) {

  File[] files = file.listFiles();

  for(File aFile : files) {

   if(aFile.isDirectory()) {

    System.out.println("Directory: " + aFile.getName());

    listAllFiles(aFile);

   } else {

    System.out.println("File: " + aFile.getName());

   }
  }  
 }
}

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.