Only 44 hours left in the trailboss' kickstarter!

New rewards and stretch goals. CLICK HERE!



  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to delete files in a directory older than n days  RSS feed

 
riya jones
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to delete files in a directory using creation date of file to get how older they are.

Thanks in advance..
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

You can use java.io.File's listFiles methods for getting the files and sub directories inside a directory. One of those methods takes a java.io.FileFilter. If you create your own implementation and inside the accept(File) method check if a) the file is a file (isFile()), and b) if it's too old (use lastModified()), then you can list only those files that are too old. Calling delete() on each of those files will then delete them.
 
riya jones
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor wrote:Welcome to the Ranch!

You can use java.io.File's listFiles methods for getting the files and sub directories inside a directory. One of those methods takes a java.io.FileFilter. If you create your own implementation and inside the accept(File) method check if a) the file is a file (isFile()), and b) if it's too old (use lastModified()), then you can list only those files that are too old. Calling delete() on each of those files will then delete them.



Thanks Rob.But I want to do this with [u]creation date of a file[/u] not last modified date.Any suggestion..
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
riya jones wrote:

Thanks Rob.But I want to do this with [u]creation date of a file[/u] not last modified date.Any suggestion..


I think I just saw another thread here that said that the nio package in Java 7 has a method to get the creation date. If you're not on 7 yet, you're probably out of luck for a pure Java solution.
 
Rob Spoor
Sheriff
Posts: 20893
81
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeff's right, and even in Java 7 there are no guarantees that you get what you want. From the Javadoc page of the creationTime() method of BasicFileAttributes:
If the file system implementation does not support a time stamp to indicate the time when the file was created then this method returns an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z).
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!