Skip to content
Advertisement

Java – Read files in a directory to a HashMap – recursive

Here below am trying to read fileNames from a nested folder structure into a hashmap,
Structure is like

JavaScript

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.

JavaScript

Please help me find out where am going wrong.

Input is the path of the parent directory.

Expected Output:

JavaScript

Thank You.

Advertisement

Answer

JavaScript

There are very minute changes need to be done in your code.

  1. 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.
  2. 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.
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement