如何根据 "last modified" 计算每小时的文档数量

How to calculate number of documents per hour depending on their "last modified"

我正在开发一种工具来计算来自另一个程序的存档文件。因此,我使用 DirectoryStream 和过滤器子目录以及一些带有简单 if 子句的文件(如下所示)。

我想统计一下,平均每小时创建了多少文档。

我在处理文件和目录方面不是很有经验,但我想有某种方法 "getLastModified",获取从最旧到最年轻的时间范围并计算每小时的平均文档数?

嗯,文件有一个 lastModified() method, returning the timestamp of last modification. It returns 0 if the file does not exist or an I/O error occurred. To convert a Path to a File you can use the toFile() 方法。这样,计算 files/hour 平均值将相当容易:

long minTimestamp = Long.MAX_VALUE; // definitely greater than any timestamp you will ever find
long maxTimestamp = 0;
int count = 0;

try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(Paths.get("DIRECTORY PATH"))) {
    for(Path path: directoryStream) {
        if (!(Files.isDirectory(path) || path.toString().endsWith("\databaseinfo.xml") || path.toString().endsWith(".log"))) {
            long lastModified = path.toFile().lastModified();
            if (lastModified > 0L) { // check that no error occurred
                if (lastModified < minTimestamp) minTimestamp = lastModified; // new minimum
                if (maxTimestamp < lastModified) maxTimestamp = lastModified; // new maximum
            }
            count = count + 1;
        }
    }

} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(count);
double filesPerHour = 0;
if (maxTimestamp != minTimestamp) { // avoid division by 0
    filesPerHour = (double) count * 60 * 60 * 1000 / (maxTimestamp - minTimestamp); // 60 * 60 * 1000 = milliseconds in one hour
}
System.out.println(filesPerHour);

编辑:反转 if 条件,以避免在 else 块中有代码的空 if 语句