- 我没有使用java 8(Date + Time API ...) - 我正在使用Java SE 7
我在这里要完成的是以毫秒为单位获取父目录内目录的最后修改时间,以毫秒为单位获取系统的当前时间,然后比较它们(如果......则删除)
这似乎不起作用..
代码:
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = MyParentDirectory.listFiles();
for(File f : subf){
if(f.isDirectory()){
if((Calendar.getInstance().get(Calendar.MILLISECOND) - (f.lastModified() + 1000)) > sec){//The comparison
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length +" folders" + "\n");
}
答案 0 :(得分:0)
看起来,我的Windows上的File#lastModified()存在一些问题,也许对你来说是一样的。试试这个:
private long getSecondsFromModification(File f) throws IOException {
Path attribPath = f.toPath();
BasicFileAttributes basicAttribs
= Files.readAttributes(attribPath, BasicFileAttributes.class);
return (System.currentTimeMillis()
- basicAttribs.lastModifiedTime().to(TimeUnit.MILLISECONDS))
/ 1000;
}
private void deleteFolders(int sec) {
int counter = 0;
File subf[] = myParentDirectory.listFiles();
for (File f : subf) {
if (f.isDirectory()) {
try {
if (getSecondsFromModification(f) > sec) {
f.delete();
System.out.print("Deleted " + f.getName() + "\n");
counter++;
}
} catch (IOException ex) {
System.out.println("Unable to access file " + f.getName() + " informtaion");
}
}
}
System.out.print("Deleted " + counter + " out of " + subf.length + " folders" + "\n");
}