我怎样才能从目录中的每个文件中获取日期?
let directoryContent = try fileManager.contentsOfDirectory(atPath: directoryURL.path)
Run Code Online (Sandbox Code Playgroud)
这就是我从目录中获取文件的方式.我发现了一些方法:
directoryContent.Contains(...)
数据较旧的文件几天 - 我怎么检查它?
然后;
let fileAttributes = try fileManager.attributesOfItem(atPath: directoryURL.path)
Run Code Online (Sandbox Code Playgroud)
它将在目录中给我最后一个文件.
这将以字节为单位返回日期:
for var i in 0..<directoryContent.count {
let date = directoryContent.index(after: i).description.data(using: String.Encoding.utf8)!
print(date)
}
Run Code Online (Sandbox Code Playgroud)
哪一个是从所有文件中恢复日期的最佳方法,或检查目录是否对比X时间早的特定日期.
提前致谢!
强烈建议使用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)
}
Run Code Online (Sandbox Code Playgroud)
如果您希望更好地控制工作流,例如URL无效并且您想要打印错误的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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
895 次 |
| 最近记录: |