'How to delete older files
I'm going to make a logic to erase files from a year ago. Does anyone know if there is a process that allows you to read the oldest file first without reading the entire file before erasing it with the delete() method using the File Class?
I'm looking for a way to get the same performance even if there are 10,000 to 1 million files.
public class FileValidation {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
long todayMil = cal.getTimeInMillis();
long oneDayMil = 24 * 60 * 60 * 1000;
Calendar fileCal = Calendar.getInstance();
Date fileDate = null;
File path = new File("C:\\test");
File[] list = path.listFiles();
for (int j = 0; j < list.length; j++) {
fileDate = new Date(list[j].lastModified());
fileCal.setTime(fileDate);
long diffMil = todayMil - fileCal.getTimeInMillis();
int diffDay = (int) (diffMil / oneDayMil);
if (diffDay > 3 && list[j].exists()) {
list[j].delete();
}
}
}
}
Solution 1:[1]
It is generally better to avoid Date and File handling. In newer JDKs the Path, Files and java.time.* classes gives much better control over filesystem and time handling.
It is easy to setup a reference time (example 365 days ago), and use Files.find to perform the scan of matching files older than this period:
Path dir = Path.of("C:/test");
Instant refTime = Instant.now().minus(Duration.ofDays(365));
try(var files = Files.find(dir, /*depth*/ Integer.MAX_VALUE, (p,a) ->
a.isRegularFile() && a.lastModifiedTime().toInstant().isBefore(refTime))) {
files.forEach(System.out::println);
}
Change the above to perform delete, I've not left it there in case someone accidentally runs it, replace action with:
files.forEach(p -> {
try {
Files.delete(p);
} catch(IOException io) {
throw new UncheckedIOException(io);
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
