快速递归列出文件夹中的所有文件 [英] listing all files in a folder recursively with swift
问题描述
我正在学习快速,想知道在目录中列出具有绝对路径的所有文件的最佳方法是什么,包括子文件夹(仅文件)中的文件
I'm learning swift and wondering what's the best way to list all files with absolute path in a directory including ones from subfolders(files only)
我尝试了以下操作,但似乎列出了所有内容名称,甚至没有完整路径的文件夹名称.
I tried with following, but it seems listing all contents names even folder names without full paths.
let paths = FileManager.default.subpaths(atPath: folderPath)
for p in paths! {
print p
}
}
以及
让项目=尝试fm.contentsOfDirectory(atPath:folderPath)
搜索没有任何可行的方法.
googling didn't come out with any working methods.
这是针对macOS 10.14
this is for macOS 10.14
感谢您的帮助!
谢谢
推荐答案
FileManager
has also a method for a deep search: enumerator(at:includingPropertiesForKeys:options:errorHandler:)
要仅获取文件,您必须迭代枚举器并过滤文件
To get only the files you have to iterate the enumerator and filter the files
let url = URL(fileURLWithPath: "/path/to/directory")
var files = [URL]()
if let enumerator = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles, .skipsPackageDescendants]) {
for case let fileURL as URL in enumerator {
do {
let fileAttributes = try fileURL.resourceValues(forKeys:[.isRegularFileKey])
if fileAttributes.isRegularFile! {
files.append(fileURL)
}
} catch { print(error, fileURL) }
}
print(files)
}
强烈建议使用URL而不是字符串路径.
It's highly recommended to use URLs rather than string paths.
这篇关于快速递归列出文件夹中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!