Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for all txt files in directory - Swift

Tags:

file

search

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.

like image 666
user5976686 Avatar asked Feb 24 '16 20:02

user5976686


3 Answers

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.

like image 52
Jay Mehta Avatar answered Oct 14 '22 00:10

Jay Mehta


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
like image 8
Sandeep Avatar answered Oct 14 '22 00:10

Sandeep


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)
like image 7
Dani.Rangelov Avatar answered Oct 13 '22 22:10

Dani.Rangelov