How can I find out when a file was created using java, as I wish to delete files older than a certain time period, currently I am deleting all files in a directory, but this is not ideal:
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
DeleteFiles(file);
File file2 = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/");
DeleteFilesNonPdf(file2);
}
public void DeleteFiles(File file) {
System.out.println("Now will search folders and delete files,");
if (file.isDirectory()) {
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
Above is my current code, I am trying now to add an if statement in that will only delete files older than say a week.
EDIT:
@ViewScoped
@ManagedBean
public class Delete {
public void DeleteFiles() {
File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
System.out.println("Called deleteFiles");
DeleteFiles(file);
File file2 = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/");
DeleteFilesNonPdf(file2);
}
public void DeleteFiles(File file) {
System.out.println("Now will search folders and delete files,");
if (file.isDirectory()) {
System.out.println("Date Modified : " + file.lastModified());
for (File f : file.listFiles()) {
DeleteFiles(f);
}
} else {
file.delete();
}
}
Adding a loop now.
EDIT
I have noticed while testing the code above I get the last modified in :
INFO: Date Modified : 1361635382096
How should I code the if loop to say if it is older than 7 days delete it when it is in the above format?
You can use
File.lastModified()
to get the last modified time of a file/directory.Can be used like this:
Which deletes files older than
x
(anint
) days.Here is the code to delete files which are not modified since six months & also create the log file.
Need to point out a bug on the first solution listed, x * 24 * 60 * 60 * 1000 will max out int value if x is big. So need to cast it to long value
Using Apache utils is probably the easiest. Here is the simplest solution I could come up with.
For a JDK 8 solution using both NIO file streams and JSR-310
The sucky thing here is the need for handling exceptions within each lambda. It would have been great for the API to have
UncheckedIOException
overloads for each IO method. With helpers to do this one could write:Using lambdas (Java 8+)
Non recursive option to delete all files in current folder that are older than N days (ignores sub folders):
Recursive option, that traverses sub-folders and deletes all files that are older than N days: