Tuesday, August 26, 2008

Find the number of days since a file was modified.

Many of us have come across a situation where progrmatically we are called upon to delete certain files meeting certain conditions for example: delete all files in the folder that are older than 40 days.
This is how you may solve this problem:
assumption: The base directory where the files are located is: /root/vivek/logs

let us write a simple class that does this:

Here are the steps:
1> Read the directory for files.
2> Find the last modified date for the file.
3> negete it with todays date which gives us the number of days since the file is modiefied.
4> if the number of days > 40 we delete the file.



package testing;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DeleteOldFiles {
//The file object from which we get directory listing of all files.
private File file=null;
public DeleteOldFiles(String directoryPath)
{
file=new File(directoryPath);
}

public List getFileList()
{
ArrayList files=new ArrayList();
String[] dirListing=file.list();
String path=file.getPath();
for(String entity: dirListing)
{
File tmp=null;
tmp=new File(path+"/"+entity);
if(tmp.isFile())
{

//new StringBuffer().append(path).append("/").append(entity).toString()
files.add(tmp.getPath());
}
}

return files;

}

public void deleteFilesWhichAreOld()
{
List fileList=getFileList();
Calendar todaysDate=Calendar.getInstance();
long todaysDateInMilliSec=todaysDate.getTimeInMillis();

for(String file: fileList)
{
File tmp=new File(file);
long lastModifiedDateInMilli=tmp.lastModified();

long diff=todaysDateInMilliSec-lastModifiedDateInMilli;
//The total number of milli secs in a day is 1000 (1 sec=1000 milli sec)
//1000*60(sec)*60(mins)*24(hours)
long days=diff/(1000*60*60*24);

if(days>=40)
{
boolean success;
success=tmp.delete();
if (!success)
throw new IllegalArgumentException();
}


}

}

public static void main(String[] args) {

DeleteOldFiles deFiles=new DeleteOldFiles("/temp");
deFiles.deleteFilesWhichAreOld();
}

}

No comments: