Saturday 12, Apr 2025
We are moved to new domain
Click -> www.ehowtonow.com
Wednesday, 24 May 2017

How to traverse the directories using Java

This program explains how to traverse the directories and sub directories using Java
DirectoryTraversal.java
package com.javatutorialcorner.directory;

import java.io.File;

public class DirectoryTraversal {
  
    public static void traverseDirectory(File directory) {
       System.out.println(directory);
       if (directory.isDirectory()) {
          String[] subDirectory = directory.list();
          
          for (int i = 0; i < subDirectory.length; i++) {
             traverseDirectory(new File(directory, subDirectory[i])); 
          } 
       } 
    }
    
    public static void main(String[] argv) throws Exception { 
        System.out.println("Directory traversed : ");
        File directory = new File("C://JTC");
        traverseDirectory(directory);
     }

}
Output

Directory traversed :
C:\JTC
C:\JTC\Java
C:\JTC\Java\Examples
C:\JTC\Java\Examples\Directory
C:\JTC\Java\Examples\Directory\File

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer

Related Posts:

  • How to compare paths of two file using Java Following example shows how to compare paths of two file using file1.compareTo() method in Java. compareTo public int compareTo(File pathname)  Compares two abstract pathnames lexicographically. The ordering defined by… Read More
  • How to create temp file using Java Following example shows how to create temp file using file.createTempFile() method in Java. createTempFile public static File createTempFile(String prefix,String suffix) throws IOException Creates an empty file in the defaul… Read More
  • How to get file size using Java Following example shows how to get file size in bytes using file.length() method in Java. lengthpublic long length() Returns the length of the file denoted by this abstract pathname. The return value is unspecified if this … Read More
  • How to get File Last modified Date in Java Following example shows how to get file last modified date using file.lastModified() method in Java. lastModified public long lastModified()  Returns the time that the file denoted by this abstract pathname was last mo… Read More
  • How to delete file using Java Following example shows how to delete file using file.delete() method in Java. delete public boolean delete() Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the … Read More
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: How to traverse the directories using Java Rating: 5 Reviewed By: eHowToNow