简体   繁体   中英

Search for all txt files in directory - Swift

a. How should I get all the txt files in directory?

i got a path of directory and now i should find all the txt files and change every one a little.

i try to run over all the files:

let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)
while let element = enumerator?.nextObject() as? String {

    }
}

but I stuck there. How can I check if the filetype is text?

b. When i get to a directory (in the directory I run), I want get in and search there too, and in the end get out to the place I was and continue.

a is much more important to me but if I get an answer to b too it will be nice.

a. Easy and simple solution for Swift 3:

let enumerator = FileManager.default.enumerator(atPath: folderPath)
let filePaths = enumerator?.allObjects as! [String]
let txtFilePaths = filePaths.filter{$0.contains(".txt")}
for txtFilePath in txtFilePaths{
    //Here you get each text file path present in folder
    //Perform any operation you want by using its path
}

Your task a is completed by above code.

When talking about b, well you don't have to code for it because we are here using a enumerator which gives you the files which are inside of any directory from your given root directory.

So the enumerator does the work for you of getting inside a directory and getting you their paths.

You can use for .. in syntax of swift to enumerate through NSEnumerator.

Here is a simple function I wrote to extract all file of some extension inside a folder.

func extractAllFile(atPath path: String, withExtension fileExtension:String) -> [String] {
    let pathURL = NSURL(fileURLWithPath: path, isDirectory: true)
    var allFiles: [String] = []
    let fileManager = NSFileManager.defaultManager()
    if let enumerator = fileManager.enumeratorAtPath(path) {
        for file in enumerator {
            if let path = NSURL(fileURLWithPath: file as! String, relativeToURL: pathURL).path
                where path.hasSuffix(".\(fileExtension)"){
                allFiles.append(path)
            }
        }
    }
    return allFiles
}



let folderPath = NSBundle.mainBundle().pathForResource("Files", ofType: nil)
let allTextFiles = extractAllFile(atPath: folder!, withExtension: "txt") // returns file path of all the text files inside the folder

I needed to combine multiple answers in order to fetch the images from a directory and I'm posting my solution in Swift 3

func searchImages(pathURL: URL) -> [String] {
    var imageURLs = [String]()
    let fileManager = FileManager.default
    let keys = [URLResourceKey.isDirectoryKey, URLResourceKey.localizedNameKey]
    let options: FileManager.DirectoryEnumerationOptions = [.skipsPackageDescendants, .skipsSubdirectoryDescendants, .skipsHiddenFiles]

    let enumerator = fileManager.enumerator(
        at: pathURL,
        includingPropertiesForKeys: keys,
        options: options,
        errorHandler: {(url, error) -> Bool in
            return true
    })

    if enumerator != nil {
        while let file = enumerator!.nextObject() {
            let path = URL(fileURLWithPath: (file as! URL).absoluteString, relativeTo: pathURL).path
            if path.hasSuffix(".png"){
                imageURLs.append(path)
            }
        }
    }

    return imageURLs
}

and here is a sample call

let documentsDirectory = FileManager.default.urls(for:.documentDirectory, in: .userDomainMask)[0]
let destinationPath = documentsDirectory.appendingPathComponent("\(filename)/")

searchImages(pathURL: projectPath)

Swift 4

let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let url = URL(fileURLWithPath: documentsPath)

let fileManager = FileManager.default
let enumerator: FileManager.DirectoryEnumerator = fileManager.enumerator(atPath: url.path)!
while let element = enumerator.nextObject() as? String, element.hasSuffix(".txt") {
    // do something

}
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)
while let element = enumerator?.nextObject() as? String where element.pathExtension == "txt" {
    // element is txt file
}
let fileManager = NSFileManager.defaultManager()
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath!)!
while let element = enumerator.nextObject() as? String {
    if (element.hasSuffix(".txt")) { // element is a txt file }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM