我试着用Swift遍历Mac电脑上的目录树,不想像应用程序一样进入软件包。
这样遍历目录树可以很好地工作:
func traverseDirectoryTree(){
let path = "/Users/mica/Downloads/TEST"
let url = URL(string: path)
print("try to scan Dir")
if let enumerator = FileManager().enumerator(atPath: path) {
for file in enumerator {
let fileAttributes = enumerator.fileAttributes
guard let fileName = file as? String else {continue}
print("\(fileName)")
if let fileAttributes = fileAttributes {
print(" Size:\(fileAttributes[.size]! )")
print(" Tpye:\(fileAttributes[.type]! )")
print(" Tpye:\(fileAttributes[.referenceCount]! )")
}
print("")
}
} else {
print("creating enumerator failed")
}
}
尝试排除软件包不会返回任何结果,也不会出现错误:
func traverseDirectoryTree(){
let path = "/Users/mica/Downloads/TEST"
//let url = URL(string: path)
let url = URL(filePath: path)
print("try to scan Dir")
// if let enumerator = FileManager().enumerator(atPath: path) {
if let enumerator = FileManager().enumerator( at: url!,
includingPropertiesForKeys: [.nameKey, .isDirectoryKey, .fileSizeKey],
options: [.skipsPackageDescendants]
){
for file in enumerator {
let fileAttributes = enumerator.fileAttributes
guard let fileName = file as? String else {continue}
print("\(fileName)")
if let fileAttributes = fileAttributes {
print(" Size:\(fileAttributes[.size]! )")
print(" Tpye:\(fileAttributes[.type]! )")
print(" Tpye:\(fileAttributes[.referenceCount]! )")
}
print("")
}
} else {
print("creating enumerator failed")
}
}
1条答案
按热度按时间55ooxyrt1#
在评论的帮助下,它的工作原理如下: