使用swift的filemanager迭代文件夹及其子文件夹中的文件(代码片段)

author author     2023-05-13     613

关键词:

我是编程Swift的新手,我正在尝试遍历文件夹中的文件。我看了一下here的答案并尝试将其翻译成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'

我的目的是查看主文件夹中包含的所有子文件夹和文件,找到具有特定扩展名的所有文件,然后对它们执行某些操作。

答案

使用nextObject()enumerator方法:

while let element = enumerator?.nextObject() as? String 
    if element.hasSuffix("ext")  // checks the extension
    

另一答案

我以前的答案我的两分钱..更快速和选项:

 let enumerator = FileManager.default.enumerator(atPath: folderPath)
    while let element = enumerator?.nextObject() as? String 
        print(element)

        if let fType = enumerator?.fileAttributes?[FileAttributeKey.type] as? FileAttributeType

            switch fType
            case .typeRegular:
                print("a file")
            case .typeDirectory:
                print("a dir")
            
        

    
另一答案

添加到vadian的响应 - Apple文档提到基于路径的URL在某些方面更简单,但是文件引用URL的优点是,如果在应用程序运行时移动或重命名文件,引用仍然有效。

从“访问文件和目录”的文档:

“基于路径的URL更易于操作,更易于调试,并且通常是NSFileManager等类的首选。文件引用URL的一个优点是,当您的应用程序运行时,它们不如基于路径的URL脆弱。如果用户在Finder中移动文件,任何引用该文件的基于路径的URL都会立即变为无效,并且必须更新到新路径。但是,只要文件移动到同一磁盘上的另一个位置,其唯一ID就不会更改和任何文件引用URL仍然有效。“

https://developer.apple.com/library/content/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html

另一答案

如果要分类检查元素是文件还是子目录:

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
    

另一答案

最近在处理一系列网址时遇到了困难,无论它们是否是目录(例如拖放)。在swift 4中加入此扩展,可能会有用

extension Sequence where Iterator.Element == URL 

    var handleDir: [URL] 
        var files: [URL] = []
        self.forEach  u in
            guard u.hasDirectoryPath else  return files.append(u.resolvingSymlinksInPath()) 
            guard let dir = FileManager.default.enumerator(at: u.resolvingSymlinksInPath(), includingPropertiesForKeys: nil) else  return 
            for case let url as URL in dir 
                files.append(url.resolvingSymlinksInPath())
            
        
        return files
    

另一答案

避免使用参考URL,虽然它们确实具有上述优点,它们会占用系统资源,如果您要枚举大型文件系统(实际上并不大),您的应用程序将快速进入系统墙并被macOS关闭。

另一答案

如今(2017年初),强烈建议使用 - 更通用的 - 与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的解决方案; while循环从未收到任何东西。但是,我确实遇到过这个适用于我的解决方案(在Xcode 6 beta 6中,所以自从pNre发布上述答案后,情况可能已经发生了变化?):

for url in enumerator!.allObjects 
    print("((url as! NSURL).path!)")

另一答案

返回目录中的所有文件+子目录中的文件

import Foundation

let path = "<some path>"

let enumerator = FileManager.default.enumerator(atPath: path)

while let filename = enumerator?.nextObject() as? String 
        print(filename)

另一答案

如果你得到了

“NSDirectoryEnumerator?没有名为'nextObject'的成员错误

while循环应该是:

while let element = enumerator?.nextObject() as? String 
  // do things with element

它与optional chaining有关

另一答案

斯威夫特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)
    
)
另一答案

SWIFT 3.0

返回传递的目录及其子目录中具有扩展名的所有文件

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

另一答案

Swift3 + absolute urls

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 ....
    

读取文件内容不使用 FileManager

】读取文件内容不使用FileManager【英文标题】:ReadingContentsofFileNotWorkingwithFileManager【发布时间】:2019-04-2918:47:38【问题描述】:我是Swift的新手。我正在尝试编写一个简单的应用程序,它只读取文件并将其内容转换为字符串。我... 查看详情

如何使用 Swift 处理错误(FileManager 和其他一般)[关闭]

】如何使用Swift处理错误(FileManager和其他一般)[关闭]【英文标题】:HowtohandleerrorswithSwift(FileManagerandothersingeneral)[closed]【发布时间】:2017-01-2105:25:13【问题描述】:注意:我之前发布了一个懒惰的问题,用于将代码转换为Swift3... 查看详情

FileManager MoveItem 回调 - Swift

】FileManagerMoveItem回调-Swift【英文标题】:FileManagerMoveItemCallback-Swift【发布时间】:2018-07-3108:50:56【问题描述】:我正在使用FileManager在我的应用程序中编辑、移动和删除文件。但是如何确定方法moveItem已完成?有没有可能的回调... 查看详情

如何在 swift 中使用 fileManager.unmountVolume

】如何在swift中使用fileManager.unmountVolume【英文标题】:howtousefileManager.unmountVolumeinswift【发布时间】:2018-04-0321:23:33【问题描述】:我正在尝试快速弹出/卸载USB驱动器我想我必须使用fileManager.unmountVolumeleturlString="/Volumes/UNTITLED/".ad... 查看详情

swift使用filemanager保存/检索数据(代码片段)

查看详情

如何在 Swift 4 中修改 fileManager url 以指向另一个目录

】如何在Swift4中修改fileManagerurl以指向另一个目录【英文标题】:HowtomodifythefileManagerurlinSwift4topointtoanotherdirectory【发布时间】:2017-12-1616:21:08【问题描述】:我有一个正在Xcode9.2和Swift4中开发的应用程序,它创建一个文件并将其... 查看详情

iOS 中 FileManager 的内容在哪里?

】iOS中FileManager的内容在哪里?【英文标题】:WherearethecontentsofFileManageriniOS?【发布时间】:2019-05-1809:02:10【问题描述】:我使用下面的swift代码在我的ios应用程序中创建了一个文件。letlocalFileName=String("file.rtf")lettext=String(“filecon... 查看详情

FileManager.urls 返回错误

】FileManager.urls返回错误【英文标题】:FileManager.urlsreturningerror【发布时间】:2016-10-1621:52:05【问题描述】:我最近将我的项目转换为Swift3,而且在大多数情况下,它看起来还不错。但是,我收到与FileManager相关的错误消息:“在... 查看详情

Swift 3 FileManager.default(......).first 是啥意思?

】Swift3FileManager.default(......).first是啥意思?【英文标题】:Swift3whatmeansFileManager.default(......).first?Swift3FileManager.default(......).first是什么意思?【发布时间】:2017-10-0718:29:20【问题描述】:guardletdirectoryURL=FileManager.default.u 查看详情

“FileManager”类型的值没有成员“urlsForDirectory”-AppDelegate Swift 3 错误

】“FileManager”类型的值没有成员“urlsForDirectory”-AppDelegateSwift3错误【英文标题】:Valueoftype\'FileManager\'hasnomember\'urlsForDirectory\'-AppDelegateSwift3Error【发布时间】:2016-08-1116:02:12【问题描述】:自从我最近更新到XCode8Beta5以来,我... 查看详情

在ios中使用swift删除文件

】在ios中使用swift删除文件【英文标题】:deleteafileusingswiftinios【发布时间】:2017-02-0414:18:46【问题描述】:funcgetDocumentsDirectory()->URLletpaths=FileManager.default.urls(for:.documentDirectory,in:.userDomainMask)letdocumentsDirectory=paths 查看详情

如何使用 FileManager 在 iOS 中写入文件?

】如何使用FileManager在iOS中写入文件?【英文标题】:HowdoIwriteafileiniOSusingFileManager?【发布时间】:2018-07-2107:00:17【问题描述】:我有以下代码,其中语句旁边的cmets中的打印语句的结果:letmyImageData=FileManager.default.contents(atPath:myU... 查看详情

使用 FileManager 保存/创建要作为文件处理的文件夹

】使用FileManager保存/创建要作为文件处理的文件夹【英文标题】:Save/createfolderthatittobetreatedasafilewithFileManager【发布时间】:2019-11-2914:46:49【问题描述】:我有一个iOS/CatalystMacOS应用程序,可以创建、保存、打开自定义文本文件... 查看详情

FileManager.default.contentsOfDirectory 在 swift 3 中失败

】FileManager.default.contentsOfDirectory在swift3中失败【英文标题】:FileManager.default.contentsOfDirectoryfailinswift3【发布时间】:2017-01-1714:03:23【问题描述】:我在目标-c中有代码,如下所示:-(NSArray*)PDFInDirectory:(NSString*)directoryPathNSFileManager* 查看详情

文件夹操作大全(swift)

...件,写文件等,对文件和文件夹的操作,这时就可以使用FileManager,FileHandle等类来实现。下面总结了各种常用的操作:假设用户文档下Document有如下文件和文件夹:test1.txt、fold1/test2.txt(1)首先我们获取用户文档目录路径(2).对... 查看详情

FileManager 文件将保存多少数据?

】FileManager文件将保存多少数据?【英文标题】:HowmuchdatawillFileManagerfilesave?【发布时间】:2018-03-2820:53:46【问题描述】:我在Ios中使用FileManager来创建目录并将我的日志文件保存在其中。当我得到字符串数据时,我将其附加到Fil... 查看详情

iOS无法使用FileManager访问应用程序组文件夹[重复]

】iOS无法使用FileManager访问应用程序组文件夹[重复]【英文标题】:iOScan\'tvisittheappgroupfolderwithFileManager[duplicate]【发布时间】:2020-09-2503:36:16【问题描述】:我使用以下代码将png文件写入AppGroup文件夹以在我的共享扩展和App之间共... 查看详情

swift文件读写

...;    letdoc:String=NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory,FileManager.SearchPathDomainMask.userDomainMask,true).last!       letpath= 查看详情