Read and write a String from text file

前端 未结 21 1423
别跟我提以往
别跟我提以往 2020-11-22 00:02

I need to read and write data to/from a text file, but I haven\'t been able to figure out how.

I found this sample code in the Swift\'s iBook, but I still don\'t kno

相关标签:
21条回答
  • 2020-11-22 00:57

    Earlier solutions answers question, but in my case deleting old content of file while writing was a problem.

    So, I created piece of code for writing to file in documents directory without deleting previous content. You probably need better error handling, but I believe it's good starting point. Swift 4. Usuage:

        let filename = "test.txt"
        createOrOverwriteEmptyFileInDocuments(filename: filename)
        if let handle = getHandleForFileInDocuments(filename: filename) {
            writeString(string: "aaa", fileHandle: handle)
            writeString(string: "bbb", fileHandle: handle)
            writeString(string: "\n", fileHandle: handle)
            writeString(string: "ccc", fileHandle: handle)
        }
    

    Helper methods:

    func createOrOverwriteEmptyFileInDocuments(filename: String){
        guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            debugPrint("ERROR IN createOrOverwriteEmptyFileInDocuments")
            return
        }
        let fileURL = dir.appendingPathComponent(filename)
        do {
            try "".write(to: fileURL, atomically: true, encoding: .utf8)
        }
        catch {
            debugPrint("ERROR WRITING STRING: " + error.localizedDescription)
        }
        debugPrint("FILE CREATED: " + fileURL.absoluteString)
    }
    
    private func writeString(string: String, fileHandle: FileHandle){
        let data = string.data(using: String.Encoding.utf8)
        guard let dataU = data else {
            debugPrint("ERROR WRITING STRING: " + string)
            return
        }
        fileHandle.seekToEndOfFile()
        fileHandle.write(dataU)
    }
    
    private func getHandleForFileInDocuments(filename: String)->FileHandle?{
        guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            debugPrint("ERROR OPENING FILE")
            return nil
        }
        let fileURL = dir.appendingPathComponent(filename)
        do {
            let fileHandle: FileHandle? = try FileHandle(forWritingTo: fileURL)
            return fileHandle
        }
        catch {
            debugPrint("ERROR OPENING FILE: " + error.localizedDescription)
            return nil
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:59

    For my txt file works this way:

    let myFileURL = NSBundle.mainBundle().URLForResource("listacomuni", withExtension: "txt")!
    let myText = try! String(contentsOfURL: myFileURL, encoding: NSISOLatin1StringEncoding)
    print(String(myText))
    
    0 讨论(0)
  • 2020-11-22 00:59

    write in ViewDidLoad

    var error: NSError?
    var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
    var documentsDirectory = paths.first as String
    var dataPath = documentsDirectory.stringByAppendingPathComponent("MyFolder")
    
    if !NSFileManager.defaultManager().fileExistsAtPath(dataPath) {
        NSFileManager.defaultManager().createDirectoryAtPath(dataPath, withIntermediateDirectories: false, attributes: nil, error: &error)
    } else {
        println("not creted or exist")
    }
    
    func listDocumentDirectoryfiles() -> [String] {
        if let documentDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as? String {
            let myFilePath = documentDirectory.stringByAppendingPathComponent("MyFolder")
            return NSFileManager.defaultManager().contentsOfDirectoryAtPath(myFilePath, error: nil) as [String]
        }
        return []
    }
    
    0 讨论(0)
提交回复
热议问题