I am trying to delete a particular folder in Java and I am using Apache Commons class to do the job. If there is any better option please let me know as well.
import org.apache.commons.io.FileUtils;
FileUtils.deleteDirectory(new File(destination));
Now what I need to do is - I need to find all the directories within this folder /opt/hello/world
which is X days old (here X can be 30 days) and delete all those directory one by one. These directories can contain files as well so once I delete directory, files will also get deleted . I was looking into the API and I saw AgeFilter class so I started using like this:
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AgeFileFilter;
private static final int DAYS_OLD = 30;
public void deleteFiles(File file) {
long purgeTime = System.currentTimeMillis() - (DAYS_OLD * 24L * 60L * 60L * 1000L);
Iterator<File> filesToDelete = FileUtils.iterateFiles(file, new AgeFileFilter(purgeTime), TRUE);
for (File aFile : filesToDelete) {
aFile.delete();
}
}
But I am getting this error in for loop. What wrong I am doing?
Can only iterate over an array or an instance of java.lang.Iterable
Update:-
long purgeTime = System.currentTimeMillis() - (DAYS_OLD * 24L * 60L * 60L * 1000L);
AgeFileFilter filter = new AgeFileFilter(purgeTime);
File path = new File("/opt/hello/world");
File[] oldFolders = FileFilterUtils.filter(filter, path);
for (File folder : oldFolders) {
FileUtils.deleteDirectory(folder);
}