文件从目录文件夹日期



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

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)
            }

哪一种是从所有文件中恢复日期的最佳方法或检查目录conteins特定的日期是否年龄较大。

预先感谢!

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

此代码打印指定目录的所有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: .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和相关的错误,但是继续预先填写其他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)
}

相关内容

最新更新