Read and write a String from text file

前端 未结 21 1803
别跟我提以往
别跟我提以往 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
        }
    }
    

提交回复
热议问题