Syrotek
Syrotek

Reputation: 13

Java - Check file name against current date?

I'm still very new to Java, and am making a small program that has to check a folder filled with thousands of files named after the date they were created in a YYYYMMDD format (e.g. 20130228) and if it finds that they are over a week old, move them into a new directory. At the moment my code can scan the folder and give me a list of the file names, and if it finds that there is more than one file it creates the folder they need to be moved into, but how would I actually go about doing the check on the file names and moving them if they are over 7 days old?

Here's what I have so far:

public static void main(String[] args) {
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");

    // Gets a list of files in specified folder
    File folder = new File("C:/Users/workspace/Test");
    File[] listOfFiles = folder.listFiles();
    for (File file : listOfFiles) {
        if (file.isFile()) {
            System.out.println(file.getName());
        }
    }

    // Creates a temp folder with the date if files are in the specified folder
    File file = new File("C:/Users/workspace/Test");
    if (file.isDirectory()) {
        String[] files = file.list();
        if (files.length > 0) {
            File dir = new File("Temp " + (dateFormat.format(date)));
        dir.mkdir();
        }
    }
}

Upvotes: 1

Views: 6228

Answers (5)

Basil Bourque
Basil Bourque

Reputation: 339043

A few thoughts…

Beware of omitting the time from your tracking. I know you are thinking in terms of whole days. But keep in mind that the beginning and ending of a day depends on a time zone. If you do not specify a time zone, the JVM’s default is used. That means that if you deployed your app on other computers/servers or otherwise had the computer’s/JVM’s time zone changed, you would be getting different behavior.

If you included hyphens in your format you would be following the common ISO 8601 format: YYYY-MM-DD. That format is easier to read. That format is also conveniently used by Joda-Time (explained below).

As far as I know, most file systems get cranky when you store more than two or three thousand files in a folder/directory. Either verify the behavior of your native OS’ file system, or group your files in nested folders such as by month or by year.

Joda-Time

This kind of date-time work is easier with the Joda-Time library. The java.util.Date & Calendar classes bundled with Java are notoriously troublesome and should be avoided.

In Joda-Time, if you truly are certain you want to ignore time and time zones, use the LocalDate class. Otherwise, use the DateTime class plus a DateTimeZone object.

LocalDate now = LocalDate.now();
LocalDate weekAgo = now.minusWeeks( 1 );

String input = "20130228";

DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyyMMdd" );
LocalDate fileLocalDate = formatter.parseLocalDate( input );

boolean isThisFileOld = fileLocalDate.isBefore( weekAgo );

Upvotes: 0

StarPinkER
StarPinkER

Reputation: 14271

class OldFileFilter extends FileFilter {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    public boolean accept(File f) {
        Date date = dateFormat.parse(f.getName());
        return System.currentTimeMillis() - date.getTime() > 7 * 24 * 3600 * 1000;
    }

    public String getDescription() {
        return "Filter old files";
    }
}

File[] files = dir.listFiles(new OldFileFilter());
//Then move...

For nio in Java 7, check How to replace File.listFiles(FileFilter filter) with nio in Java 7

Upvotes: 1

Sanober Malik
Sanober Malik

Reputation: 2805

You can do this by comparing the name of the file with current date :

          SimpleDateFormat formatter;
          formatter = new SimpleDateFormat("yyyyMMdd");
          Date d = null;
          try {
            d = formatter.parse(filename);//filename of the file
        } catch (ParseException e) {
            e.printStackTrace();
        }

     Date newDate = new Date();
    if (newDate.getTime() - d.getTime() > 7 * 24 * 3600 * 1000) {
        //Whatever You want to do
    }

Upvotes: 0

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136052

Parse file name, check if the difference between now and date > 7 days

Date date = dateFormat.parse(file.getName());
if (System.currentTimeMillis() - date.getTime() > 7 * 24 * 3600 * 1000) {
    // older than 7 days
}

Upvotes: 0

X-Factor
X-Factor

Reputation: 2117

There could be two solutions

1- To get file's last modification date we can use the lastModified() method of the File class. This method returns a long value. After getting this value you can create an instance of java.util.Date class and pass this value as the parameter. This Date will hold the file's last modification date.

You can get all the files and compare each files lastModified date with the date you request.

2-

public static void deleteFilesOlderThanNdays(int daysBack, String dirWay, org.apache.commons.logging.Log log) {

    File directory = new File(dirWay);
    if(directory.exists()){

        File[] listFiles = directory.listFiles();            
        long purgeTime = System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);
        for(File listFile : listFiles) {
            if(listFile.lastModified() < purgeTime) {
                if(!listFile.delete()) {
                    System.err.println("Unable to delete file: " + listFile);
                }
            }
        }
    } else {
        log.warn("Files were not deleted, directory " + dirWay + " does'nt exist!");
    }
}

here rather than delete you should move the those files to your desired folder.

Upvotes: 0

Related Questions