2017-03-03 37 views
2

如何从目录中的每个文件获取日期?目录文件夹中的文件日期

let directoryContent = try fileManager.contentsOfDirectory(atPath: directoryURL.path) 

这就是我如何从目录中获取文件。我发现了几个方法:

directoryContent.Contains(...)

的文件,其中的数据是旧的,然后几天 - 我怎么能检查呢?

然后;

let fileAttributes = try fileManager.attributesOfItem(atPath: directoryURL.path) 

它会给我目录中的最后一个文件。

而这要以字节为单位回复日期:

for var i in 0..<directoryContent.count { 
       let date = directoryContent.index(after: i).description.data(using: String.Encoding.utf8)! 
       print(date) 
      } 

哪一个是recive从所有文件的日期或检查目录conteins这是旧的,那么X时间特定日期的最佳途径。

在此先感谢!

回答

4

强烈建议使用URL相关API FileManager以非常有效的方式获取文件属性。

此代码打印指定目录的所有URL,创建日期早于一周前。

let calendar = Calendar.current 
let aWeekAgo = calendar.date(byAdding: .day, value: -7, to: Date())! 

do { 
    let directoryContent = try fileManager.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles]) 
    for url in directoryContent { 
     let resources = try url.resourceValues(forKeys: [.creationDateKey]) 
     let creationDate = resources.creationDate! 
     if creationDate < aWeekAgo { 
      print(url) 
      // do somthing with the found files 
     } 
    } 
} 
catch { 
    print(error) 
} 

如果你想例如一个URL是无效的工作流程进行更精细的控制,你要打印的不良URL和相关的错误,但继续旋进其他网址使用一个枚举,语法颇为相似:

do { 
    let enumerator = fileManager.enumerator(at: directoryURL, includingPropertiesForKeys: [.creationDateKey], options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles], errorHandler: { (url, error) -> Bool in 
     print("An error \(error) occurred at \(url)") 
     return true 
    }) 
    while let url = enumerator?.nextObject() as? URL { 
     let resources = try url.resourceValues(forKeys: [.creationDateKey]) 
     let creationDate = resources.creationDate! 
     if creationDate < last7Days { 
      print(url) 
      // do somthing with the found files 
     } 
    } 

} 
catch { 
    print(error) 
} 
+0

这就是我一直在寻找的!谢谢 ! – yerpy