读取子目录的创建日期

时间:2015-07-23 18:51:04

标签: java

我有一个主文件夹“G:\ TestFiles”。在TestFiles文件夹中,我在不同的日期创建了5个子文件夹。我想获得这些子目录的创建日期。这是我到目前为止所做的:

public static void main(String aa[]) throws IOException
{
        BasicFileAttributes bfa = null;

        File dir = new File("G:\\TestFiles");
        Path filePath = dir.toPath();

        File[] subDirs = dir.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.isDirectory();
            }
        });
        for (File subDir : subDirs)
        {

        bfa = Files.readAttributes(filePath, BasicFileAttributes.class);

        long milliseconds = bfa.creationTime().to(TimeUnit.MILLISECONDS);
        if((milliseconds > Long.MIN_VALUE) && (milliseconds < Long.MAX_VALUE))
        {
            Date creationDate = new Date(bfa.creationTime().to(TimeUnit.MILLISECONDS));

            System.out.println("File " + filePath.toString() + " created " +
                    creationDate.getDate() + "/" +
                    (creationDate.getMonth() + 1) + "/" +
                    (creationDate.getYear() + 1900));
        }
        }
}

我的输出:

File G:\TestFiles created 7/7/2015
File G:\TestFiles created 7/7/2015
File G:\TestFiles created 7/7/2015
File G:\TestFiles created 7/7/2015
File G:\TestFiles created 7/7/2015

根据我的方法,我没有得到正确的输出。谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

您始终会读取父文件夹的属性:

bfa = Files.readAttributes(filePath, BasicFileAttributes.class);

您应该阅读当前子文件夹的属性

bfa = Files.readAttributes(subDir.toPath(), BasicFileAttributes.class);