Reputation: 1
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
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
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