简体   繁体   English

如何在java中获取目录的最后修改日期和时间

[英]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() . 看,问题是在Java中,我们可以通过filename.lastModified()获得lastmodified date。 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. 但在Windows中,正在发生的事情是,无论何时修改文件,只修改该文件的日期和时间,而不是整个文件夹。 So I want to know when was the last time even one single file was modified in that folder, using Java? 所以我想知道最后一次使用Java在该文件夹中修改单个文件的时间是什么时候?

Find the latest (largest) lastModified() in the directory's files , or if there are none use the directory's itself: 在目录的文件中找到最新的(最大的) lastModified() ,如果没有,则使用目录本身:

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. 它假定提供的File是一个目录,并且还返回long而不是Date本身。 You may convert long to Date by using the Date 's constructor if required (which is normally not needed). 如果需要,您可以使用Date的构造函数将long转换为Date (通常不需要)。

Here is a Java 7 solution using FileTime and Path : 这是使用FileTimePathJava 7解决方案:

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 . 这已经从衍生掉了Oracle教程这里

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. 因此,当您比较java程序和操作系统的最后修改日期时,它可能会有所不同。

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. 对于目录和任何子目录中的每个文件,执行lastModified ,并保留最新值。

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. latestModified是您可以使用的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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