Skip to content
Advertisement

Rename all files inside subdirectories and place it in their respective parent directory in destination folder

I have below folder structure

JavaScript

I want to loop directory one by one and then convert the filename into uppercase, for single word like bonnet.png it should be BONNET.png, but for filename having spaces like center of front bumper, it should be CENTER_OF_FRONT_BUMPER.png.

the output should be like below

JavaScript

I have written a below code but it is not working as per expectaiton.

firstly it able to make the filename in uppercase(not appended underscore), but it doesn’t create the parent directory and without creating the parent directory it copies the files inside that.

JavaScript

Advertisement

Answer

Using File and recursive File.listFiles() makes the logic harder to follow. Consider switching to Files.find which can produce a directory scan with a small amount of code:

JavaScript

The above just prints names of files to process. Then you can swap the action for something that performs the rename, and can be adjusted to apply the action constructing directories before copying:

JavaScript

It’s never a good idea to generate files into the directory you scan – as that means you cannot re-run on same input as you will be doubling the number of files.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement