Traversing Directories in Java

Here you will learn how to traverse directories in Java Programming Language. This tutorial will include some easy tricks to understand the problem.

Traversing Directories

As of to traverse any specific directory, we will use some predefined methods,

  • file.list()
  • file.isDirectory

These are the existing methods of the File class that we will be including under the Main() class of our java file, which will be helpful to extract the child files from the mentioned input file path.

Implementation:

we will be declaring a function that basically will extract the child directories and files for the given path

 public static void visitAll(File file) 
{
  System.out.println(file);
  if (file.isDirectory()) {
      String[] child = file.list();
      for (int i = 0; i < child.length; i++) {
          visitAll(new File(file, child[i])); 
      } 
  } 
}

Next, we will have to mention the path of the directory we want to traverse and check whether the directory exists or not. If not then we have to invoke the getParent() method to the parent directory. We have called the visitAll() method for getting the following child directories.

public static void main(String[] argv) throws Exception
{ 
  System.out.println("The Directory is traversed.");
  File file = new File("C:\\Users\\store\\Desktop\\Extension Chrome1");
  if(!file.exists()){
     file = file.getParentFile();
  }
  visitAll(file);
}

Output:

The Directory is traversed.
C:\Users\store\Desktop\Extension Chrome1
C:\Users\store\Desktop\Extension Chrome1\background.js
C:\Users\store\Desktop\Extension Chrome1\manifest.json

Note: Import the File package in your code before proceeding ‘ import java.io.File ‘

Leave a Reply

Your email address will not be published. Required fields are marked *