K. Sun
K. Sun

Reputation: 1

How to recursively retrieve files from folders returning file name and its Folder name

The code actually retrieves the files but In addition I would also like to get the name of the folder unfortunately, all I keep getting is the path to the folder. I need to extract the sub-directory's/folder's name that contains the files.

 public void listAllFilesInTheDirectory(String aDirectoryName){
   File directory = new File(aDirectoryName);
   File[] allFiles = directory.listFiles();

   for (File file : allFiles) { 
       if (file.isFile()) {
           System.out.println("File Name: "+file.getName());
           System.out.println("Parent : "+file.getParent());
        } else if (file.isDirectory()) {
            listAllFilesInTheDirectory(file.getAbsolutePath());
        }
 }
}  

The output:

Upvotes: 0

Views: 161

Answers (2)

Stefan Haustein
Stefan Haustein

Reputation: 18793

Are you looking for the parent folder name without the path? If so, use

System.out.println("Parent : "+file.getParentFile().getName());

Upvotes: 0

Nir Alfasi
Nir Alfasi

Reputation: 53525

You may want to use folderFullPath.lastIndexOf(File.separator) in order to find the index of the \ character before the folder name and then use substring to extract the folder name from the full-path.

Upvotes: 1

Related Questions