Delete files older than n days and remove the empty directories after the files are deleted. This can be done using recursion.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import java.io.File; import java.util.Calendar; public class CleanDirectories { private static boolean isFinished = false; //Remove old files, Recursion, Time O(n), Space O(n), n is number of files in directory public static void removeOldFiles(String path, long time) { File dir = new File(path); for (File file : dir.listFiles()) { if (file.isDirectory()) removeOldFiles(file.getAbsolutePath(), time); else { if (file.lastModified() < time) { System.out.println("file is deleted."); file.delete(); } } } } //Remove empty directory, Recursion, Time O(n), Space O(n) public static void cleanEmptyDirectories(String path) { File dir = new File(path); File[] files = dir.listFiles(); if (files.length == 0) { System.out.println("Folder Name :" + dir.getAbsolutePath() + " is deleted."); dir.delete(); isFinished = true; } else { for (File file : files) { if (file.isDirectory()) cleanEmptyDirectories(file.getAbsolutePath()); } } } public static void main(String[] args) { //Get current running directory final String dir = System.getProperty("user.dir"); String path = dir.replace("/", "\\\\") + "\\data\\oldfiles"; //Remove files Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -3); //3 days old files long t = cal.getTimeInMillis(); do { isFinished = true; removeOldFiles(path, t); } while (!isFinished); //Clean directories do { isFinished = true; cleanEmptyDirectories(path); } while (!isFinished); } } |
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.