从&读取和写入数据使用Swift逐步增加文档目录中的文本文件

时间:2017-11-04 17:06:06

标签: ios swift documentsdirectory

Swift 4:如您所知,以下是如何从&amp ;;读取或写入数据。使用Swift文档目录中的文本文件:

        let DocumentDirURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)

        let fileURL = DocumentDirURL.appendingPathComponent("Test").appendingPathExtension("txt")
        print("FilePath: \(fileURL.path)")

        let writeString = "Add string"

        do {
            // Write to the file

            try writeString.write(to: fileURL, atomically: true, encoding: String.Encoding.utf8)

        } catch let error as NSError {

            print("Failed writing to URL: \(fileURL), Error: " + error.localizedDescription)

        }

        var readString = "" // Used to store the file contents

        do {

            // Read the file contents

            readString = try String(contentsOf: fileURL)

        } catch let error as NSError {

            print("Failed reading from URL: \(fileURL), Error: " + error.localizedDescription)

        }

        print("File Text: \(readString)")

它会将Add string写入Test.txt文件。

下次将"Add string"更改为"Add some other string."时,Test.txt文件将更改为Add some other string.

这意味着"添加字符串"将替换为"添加其他字符串。"。但我想逐步将这两个字符串添加到Test.file中,以便Test.txt文件包含:添加字符串,添加其他字符串。

有没有办法让它成真?感谢。

0 个答案:

没有答案