使用swift递归列出文件夹中的所有文件 [英] 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
}
}
以及
let items = try fm.contentsOfDirectory(atPath: folderPath)
谷歌搜索没有找到任何工作方法.
googling didn't come out with any working methods.
这适用于 macOS 10.14
this is for macOS 10.14
感谢任何帮助!
谢谢
推荐答案
FileManager
还有一个深度搜索的方法:enumerator(at:includePropertiesForKeys:options:errorHandler:)
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.
这篇关于使用swift递归列出文件夹中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!