sansSpoon
sansSpoon

Reputation: 2185

Finding the last modified file older than 24 hours in Java

I'm wanting to send an alert if the latest modified file in a directory is older than 24 hours. I've used the tips from these two questions:

How do I find the last modified file in a directory in Java?

Changing Java Date one hour back

and have come up with:

File dir = new File("/path/to/dir");

File[] files = dir.listFiles();
if (files.length == 0) {
    return null;
}

File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
   if (lastModifiedFile.lastModified() < files[i].lastModified()) {
         Date modifiedDate = new Date(files[i].lastModified());
        return modifiedDate;
   }
}
Date currentDate = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(currentDate);
cal.add(Calendar.HOUR, -24);
Date alertDate = cal.getTime();

if (modifiedDate.before(alertDate)){
    return true;
} else {
    return false;
}

However I'm getting a "can not find symbol" modifiedDate. I realise that its because modifiedDate can't be seen by the last if statement but if I put that and the alertDate within the initial for loop then I get a "missing return statement".

Any ideas?

Upvotes: 3

Views: 6967

Answers (1)

Jerome Anthony
Jerome Anthony

Reputation: 8021

Did you try like below;

public static boolean getLastModified() throws IOException{
    File dir = new File("C:\\temp\\lot_of_files\\logs");

    File[] files = dir.listFiles();
    if (files.length == 0) {
        throw new IOException("No files to monitor in the dir");
    }

    Date modifiedDate = null;
    File lastModifiedFile = files[0];
    for (int i = 1; i < files.length; i++) {
       if (lastModifiedFile.lastModified() < files[i].lastModified()) {
            modifiedDate = new Date(files[i].lastModified());
       }
    }
    Date currentDate = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(currentDate);
    cal.add(Calendar.HOUR, -24);
    Date alertDate = cal.getTime();

    if (modifiedDate != null && modifiedDate.before(alertDate)){
        return true;
    } else {
        return false;
    }
}

This code is short term. I would personally look at developing the solution based on Java WatchService

Upvotes: 2

Related Questions