使用Swift的FileManager遍历文件夹及其子文件夹中的文件
我很新的编程一个Swift,我试图遍历文件夹中的文件。 我看了这里的答案,并试图将其翻译成Swift语法,但没有成功。
let fileManager = NSFileManager.defaultManager() let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath) for element in enumerator { //do something }
我得到的错误是:
Type 'NSDirectoryEnumerator' does not conform to protocol 'SequenceType'
我的目标是查看包含在主文件夹中的所有子文件夹和文件,并查找具有一定扩展名的所有文件,然后对其进行操作。
使用enumerator
的nextObject()
方法:
while let element = enumerator?.nextObject() as? String { if element.hasSuffix("ext") { // checks the extension } }
目前(2017年初),强烈build议使用更多function的URL相关的API
let fileManager = FileManager.default do { let resourceKeys : [URLResourceKey] = [.creationDateKey, .isDirectoryKey] let documentsURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) let enumerator = FileManager.default.enumerator(at: documentsURL, includingPropertiesForKeys: resourceKeys, options: [.skipsHiddenFiles], errorHandler: { (url, error) -> Bool in print("directoryEnumerator error at \(url): ", error) return true })! for case let fileURL as URL in enumerator { let resourceValues = try fileURL.resourceValues(forKeys: Set(resourceKeys)) print(fileURL.path, resourceValues.creationDate!, resourceValues.isDirectory!) } } catch { print(error) }
我根本无法获得pNre的解决scheme。 while循环从来没有收到任何东西。 但是,我遇到了这个解决scheme,适用于我(在Xcode 6testing版6,所以也许事情已经改变,因为pNre公布了上面的答案?):
for url in enumerator!.allObjects { print("\((url as! NSURL).path!)") }
万一你得到了
“NSDirectoryEnumerator? 没有名为“nextObject”错误的成员
while循环应该是:
while let element = enumerator?.nextObject() as? String { // do things with element }
这与可选链接有关
Swift 3
let fd = FileManager.default fd.enumerator(atPath: "/Library/FileSystems")?.forEach({ (e) in if let e = e as? String, let url = URL(string: e) { print(url.pathExtension) } })
Swift3 +绝对url
extension FileManager { func listFiles(path: String) -> [URL] { let baseurl: URL = URL(fileURLWithPath: path) var urls = [URL]() enumerator(atPath: path)?.forEach({ (e) in guard let s = e as? String else { return } let relativeURL = URL(fileURLWithPath: s, relativeTo: baseurl) let url = relativeURL.absoluteURL urls.append(url) }) return urls } }
基于@ user3441734的代码
更新Swift 3:
let fileManager = FileManager() // let fileManager = NSFileManager.defaultManager() let en=fileManager.enumerator(atPath: the_path) // let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath) while let element = en?.nextObject() as? String { if element.hasSuffix("ext") { // do something with the_path/*.ext .... } }
SWIFT 3.0
返回Directory中传递的所有文件及其子目录
func extractAllFile(atPath path: String, withExtension fileExtension:String) -> [String] { let pathURL = NSURL(fileURLWithPath: path, isDirectory: true) var allFiles: [String] = [] let fileManager = FileManager.default let pathString = path.replacingOccurrences(of: "file:", with: "") if let enumerator = fileManager.enumerator(atPath: pathString) { for file in enumerator { if #available(iOS 9.0, *) { if let path = NSURL(fileURLWithPath: file as! String, relativeTo: pathURL as URL).path, path.hasSuffix(".\(fileExtension)"){ let fileNameArray = (path as NSString).lastPathComponent.components(separatedBy: ".") allFiles.append(fileNameArray.first!) } } else { // Fallback on earlier versions print("Not available, #available iOS 9.0 & above") } } } return allFiles }
返回目录中的所有文件
Swift 3
let fileNames = try! FileManager.default.contentsOfDirectory(atPath: "/Volumes/Seagate/Path/") for fileName in fileNames { print(fileName) }
如果要分类检查一个元素是文件还是子目录:
let enumerator = FileManager.default.enumerator(atPath: contentsPath); while let element = enumerator?.nextObject() as? String { if(enumerator?.fileAttributes?[FileAttributeKey.type] as! FileAttributeType == FileAttributeType.typeRegular){ //this is a file } else if(enumerator?.fileAttributes?[FileAttributeKey.type] as! FileAttributeType == FileAttributeType.typeDirectory){ //this is a sub-directory } }