取得目录下所有文件,示例函数:
static func getAllFilePath(_ dirPath: String) -> [String]? {
var filePaths = [String]()
do {
let array = try FileManager.default.contentsOfDirectory(atPath: dirPath)
for fileName in array {
var isDir: ObjCBool = true
let fullPath = "\(dirPath)/\(fileName)"
if FileManager.default.fileExists(atPath: fullPath, isDirectory: &isDir) {
if !isDir.boolValue {
filePaths.append(fullPath)
}
}
}
} catch let error as NSError {
print("get file path error: \(error)")
}
return filePaths;
}
FileManager用来获取指定目录下的子项(文件或文件夹)列表的方法有两种:
open func contentsOfDirectory(atPath path: String) throws -> [String]
open func subpaths(atPath path: String) -> [String]?
区别是:
前者以非递归的方式获取子项列表,而后者以递归的方式获取子项列表。
网友评论