2

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?

Community
  • 1
  • 1
sansSpoon
  • 2,115
  • 2
  • 24
  • 43

1 Answers1

1

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

Jerome Anthony
  • 7,823
  • 2
  • 40
  • 31
  • Thanks for the tip, but I tried it that way and got a "Missing return Statement" – sansSpoon Dec 01 '14 at 03:42
  • Hi Jerome, thanks that has worked. This code is actually just a little scriptlet that sits inside a off-the-shelf Java scheduling and folder watching program, so no need for the watch service. Thanks for the tip though :) – sansSpoon Dec 02 '14 at 04:48