Reputation: 262
I have a main folder "G:\TestFiles". Inside TestFiles folder, I have 5 sub folders created on different dates. I want to get the creation date of those sub directories. This is what I have done so far:
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));
}
}
}
My output:
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
With my approach, I am not getting the correct output. Thank you for all your help!
Upvotes: 1
Views: 55
Reputation: 7403
You always read the attribute of the parent folder:
bfa = Files.readAttributes(filePath, BasicFileAttributes.class);
You should read the attributes of your current subfolder
bfa = Files.readAttributes(subDir.toPath(), BasicFileAttributes.class);
Upvotes: 3