Delete files older than n days recursively – code

Delete files older than n days is to delete files that are older than certain dates, and also remove the empty directories after the files are deleted. This can be done using recursion.

clean directories

Recursion is a technique that a function calls itself.  When the base condition is met, the rest of call stacks return from the last call to the first. File system is a recursive system. At root, there are directories. A directory has multiple directories and files.

All programming languages provides the classes and methods to access file system. Files and directories can be created, checked and deleted using the libraries. Our solutions will call these methods. We will use Calendar’s getTimeInMillis() to convert days to milliseconds. Compare it with file’s lastModified(). Then we can decide whether to delete files that’s older.

LinkedIn Interview Question:
Write a function that cleans out files older than a user specified number of days, and removes empty directories recursively.

Java Code:

Output:
file is deleted.
file is deleted.
file is deleted.
file is deleted.
Folder Name :folder\oldfiles\subfolder is deleted.

O notation:
Time complexity is O(n), n is the number of files/directories.
space complexity is O(m), m is the depth of the recursion.


Download CleanDirectories.java
Clean directories with recursion (YouTube)

Comments are closed