Here below am trying to read fileNames from a nested folder structure into a hashmap,
Structure is like
Main Folder -> EN (SubFolder1) -> File1 -> File2 -> FR (SubFolder2) -> File3 -> File4 -> GE (SubFolder3) -> File5 -> File6
HashMap contains “Sub FolderName” as Key & “FileNames”(ArrayList) as value.
I’m trying to make a recursive call & save things into HashMap, but missing something in that, things are not being saved into HashMap.
public static HashMap<String,ArrayList<String>> listFilesForFolder(File folder) throws IOException { HashMap<String, ArrayList<String>> dirFiles = new HashMap<String, ArrayList<String>>(); if(folder.isDirectory()) { ArrayList<String> fileNames = new ArrayList<String>(); for (final File fileEntry : folder.listFiles()) { if (fileEntry.isDirectory()) { listFilesForFolder(fileEntry); dirFiles.put(folder.getName(), fileNames); } else { String fileName = (fileEntry.getPath()).toString(); fileNames.add(fileEntry.getPath()); } } } return dirFiles; }
Please help me find out where am going wrong.
Input is the path of the parent directory.
Expected Output:
{"EN" = [File1, File2], "FR" = [File3, File4], "GE" = [File5, File6]}
Thank You.
Advertisement
Answer
public class Folder { public static HashMap<String, ArrayList<String>> dirFiles = new HashMap<String, ArrayList<String>>(); public static void listFilesForFolder(File folder) throws IOException { if(folder.isDirectory()) { ArrayList<String> fileNames = new ArrayList<String>(); for (final File fileEntry : folder.listFiles()) { // System.out.println(fileEntry.toString()); if (fileEntry.isDirectory()) { // System.out.println(fileEntry.toString()); listFilesForFolder(fileEntry); } else { String fileName = (fileEntry.getPath()).toString(); fileNames.add(fileEntry.getPath()); } } dirFiles.put(folder.getName(), fileNames); } } public static void main(String[] args) throws IOException { // TODO Auto-generated method stub listFilesForFolder(new File("C:/Users/Guest/Documents/MainFolder")); for(Entry<String, ArrayList<String>> foldername : dirFiles.entrySet()) { System.out.println(foldername.getKey() + " " + foldername.getValue()); } } }
There are very minute changes need to be done in your code.
- only when you loop through the entire list of files in folder.listFiles(), fileNames arraylist get populated with the names of files. Therefore I move the map put operation after the end of loop.
- you are creating Map object for every iteration, though you are returning map object from the function which every recursive call will do. you have to process all the map objects together. Hence a global map object.