简体   繁体   中英

How to get the last modified date and time of a directory in java

See, the problem is that in Java, we can get lastmodified date by filename.lastModified() . But in Windows, what is happening is that whenever a file is modifed, only that file's date and time are getting modified, not the whole folder's. So I want to know when was the last time even one single file was modified in that folder, using Java?

Find the latest (largest) lastModified() in the directory's files , or if there are none use the directory's itself:

public static Date getLastModified(File directory) {
    File[] files = directory.listFiles();
    if (files.length == 0) return new Date(directory.lastModified());
    Arrays.sort(files, new Comparator<File>() {
        public int compare(File o1, File o2) {
            return new Long(o2.lastModified()).compareTo(o1.lastModified()); //latest 1st
        }});
    return new Date(files[0].lastModified());
}

FYI this code has been tested (and it works).

I have written a small piece of code which does a recursive search within all subdirectories and returns the latest modification date. It does a deep search, so you may not want to run it on the root directory or so. Here is the code (I have not tested it rigorously):

private static long getLatestModifiedDate(File dir) {
    File[] files = dir.listFiles();
    long latestDate = 0;
    for (File file : files) {
        long fileModifiedDate = file.isDirectory() 
                ? getLatestModifiedDate(file) : file.lastModified();
        if (fileModifiedDate > latestDate) {
            latestDate = fileModifiedDate;
        }
    }
    return Math.max(latestDate, dir.lastModified());
}

It assumes that the supplied File is a directory, and also returns a long not a Date per se. You may convert long to Date by using the Date 's constructor if required (which is normally not needed).

Here is a Java 7 solution using FileTime and Path :

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;

import static java.nio.file.FileVisitResult.CONTINUE;

public class NewestFileVisitor extends SimpleFileVisitor<Path>
{
    private FileTime newestFileTime;
    private String targetExtension;

    public NewestFileVisitor(String targetExtension)
    {
        this.newestFileTime = FileTime.fromMillis(0);
        this.targetExtension = targetExtension;
    }

    @Override
    public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes) throws IOException
    {
        if (filePath.toString().endsWith(targetExtension))
        {
            FileTime lastModified = Files.getLastModifiedTime(filePath);

            // Newer?
            if (lastModified.compareTo(newestFileTime) > 0)
            {
                newestFileTime = lastModified;
            }
        }

        return CONTINUE;
    }

    public String getLastModified()
    {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
        long milliseconds = newestFileTime.toMillis();

        return simpleDateFormat.format(milliseconds);
    }
}

Usage:

String folder = "...";
NewestFileVisitor fileVisitor = new NewestFileVisitor(".txt");
Files.walkFileTree(Paths.get(folder), fileVisitor);
System.out.println(fileVisitor.getLastModified());

Example output:

07/08/2016 04:32 PM

This has been derived off the Oracle tutorial from here .

I believe this way you will not be able to get correct modified date for a folder because there is a case where a file is created / modified and then deleted from the folder.

Then above logic will only show the last modified date based on files present in the folder. It will not consider the one which is deleted.

So when you compare last modified date from java program and OS it may be different.

IMHO we should query OS to get last modified date for a folder.

您可以使用WatchService如果您使用的是Java7。

Well, if it is the system's or filesystem's way to record updates, then you might need to perform a recursive loop inside the directory. For each file in the directory and any subdirectory, execute lastModified , and keep the most recent value.

The way I see it, you can write something like this (untested):

long latestModified = 0;
File[] files = directory.listFiles();
for(File file : files) {
    if (latestModified < file.lastModified()) {
        latestModified = file.lastModified();
    }
}

latestModified is the variable you could use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM