【问题标题】:How to open file and append a string in it, swift如何快速打开文件并在其中附加一个字符串
【发布时间】:2015-01-15 08:33:42
【问题描述】:

我正在尝试将字符串附加到文本文件中。我正在使用以下代码。

let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String]
if (dirs) != nil {
    let dir = dirs![0] //documents directory
    let path = dir.stringByAppendingPathComponent("votes")
    let text = "some text"

    //writing
    text.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding, error: nil)

    //reading
    let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
    println(text2) //prints some text
}

这不会将字符串附加到文件中。即使我反复调用这个函数。

【问题讨论】:

  • 错误参数在某些情况下可以派上用场

标签: ios swift


【解决方案1】:

如果您希望能够控制是否追加,请考虑使用OutputStream。例如:

do {
    let fileURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
        .appendingPathComponent("votes.txt")
    
    guard let outputStream = OutputStream(url: fileURL, append: true) else {
        print("Unable to open file")
        return
    }

    outputStream.open()
    let text = "some text\n"
    try outputStream.write(text)
    outputStream.close()
} catch {
    print(error)
}

顺便说一句,这是一个扩展,可让您轻松地将String(或Data)写入OutputStream

extension OutputStream {
    enum OutputStreamError: Error {
        case stringConversionFailure
        case bufferFailure
        case writeFailure
    }

    /// Write `String` to `OutputStream`
    ///
    /// - parameter string:                The `String` to write.
    /// - parameter encoding:              The `String.Encoding` to use when writing the string. This will default to `.utf8`.
    /// - parameter allowLossyConversion:  Whether to permit lossy conversion when writing the string. Defaults to `false`.

    func write(_ string: String, encoding: String.Encoding = .utf8, allowLossyConversion: Bool = false) throws {
        guard let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) else {
            throw OutputStreamError.stringConversionFailure
        }
        try write(data)
    }

    /// Write `Data` to `OutputStream`
    ///
    /// - parameter data:                  The `Data` to write.

    func write(_ data: Data) throws {
        try data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) throws in
            guard var pointer = buffer.baseAddress?.assumingMemoryBound(to: UInt8.self) else {
                throw OutputStreamError.bufferFailure
            }

            var bytesRemaining = buffer.count

            while bytesRemaining > 0 {
                let bytesWritten = write(pointer, maxLength: bytesRemaining)
                if bytesWritten < 0 {
                    throw OutputStreamError.writeFailure
                }

                bytesRemaining -= bytesWritten
                pointer += bytesWritten
            }
        }
    }
}

对于 Swift 2 版本,请参阅此答案的 previous revision

【讨论】:

  • 当我尝试使用let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) println(text2)读取它给出的文件时为nil
  • 在尝试write 之前,您确定openNSOutputStream 吗?如果您不这样做,write 将失败。另外,在再次尝试读入文件之前,您确定是 close NSOutputStream 吗?您必须先关闭该文件,然后再尝试再次使用它。如果您仍然遇到问题,请尝试检查 write 函数的返回值,看看是否成功。
  • write 功能要求我输入maxLength。我应该放什么?
  • 是的,我在写和读之前分别打开和关闭了NSOutputStream
  • 您不应该有maxLength 参数。这意味着您调用了 write 函数的错误演绎。您是否在回答中包含了我提供的extension
【解决方案2】:

您也可以使用FileHandle 将字符串附加到您的文本文件中。如果您只想将字符串附加到文本文件的末尾,只需调用 seekToEndOfFile 方法,写入字符串数据并在完成后将其关闭:


FileHandle 使用 Swift 3 或更高版本

let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

// create a new text file at your documents directory or use an existing text file resource url
let fileURL = documentsDirectory.appendingPathComponent("simpleText.txt")
do {
    try Data("Hello World\n".utf8).write(to: fileURL)
} catch {
    print(error) 
}
// open your text file and set the file pointer at the end of it
do {
    let fileHandle = try FileHandle(forWritingTo: fileURL)
    fileHandle.seekToEndOfFile()
    // convert your string to data or load it from another resource
    let str = "Line 1\nLine 2\n"
    let textData = Data(str.utf8)
    // append your text to your text file
    fileHandle.write(textData)
    // close it when done
    fileHandle.closeFile()
    // testing/reading the file edited
    if let text = try? String(contentsOf: fileURL, encoding: .utf8) {
        print(text)  // "Hello World\nLine 1\nLine 2\n\n"
    }
} catch {
    print(error)
}

【讨论】:

    【解决方案3】:

    请检查以下代码是否适合我。只需按原样添加代码:

    let theDocumetFolderSavingFiles = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let filePath = "/theUserData.txt"
    let thePathToFile = theDocumetFolderSavingFiles.stringByAppendingString(filePath)
    let theFileManager = NSFileManager.defaultManager()
    
    if(theFileManager.fileExistsAtPath(thePathToFile)){
    
            do {
    
                let stringToStore = "Hello working fine"
                try stringToStore.writeToFile(thePathToFile, atomically: true, encoding: NSUTF8StringEncoding)
    
            }catch let error as NSError {
                print("we are geting exception\(error.domain)")
            }
    
            do{
                let fetchResult = try NSString(contentsOfFile: thePathToFile, encoding: NSUTF8StringEncoding)
                print("The Result is:-- \(fetchResult)")
            }catch let errorFound as NSError{
                print("\(errorFound)")
            }
    
        }else
        {
            // Code to Delete file if existing
            do{
                try theFileManager.removeItemAtPath(thePathToFile)
            }catch let erorFound as NSError{
                print(erorFound)
            }
        }
    

    【讨论】:

      【解决方案4】:

      检查阅读部分。

      方法cotentsOfFile:NSString类的方法。而且你用错了。

      所以替换这一行

      let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
      

      这里你必须使用NSString 而不是String 类。

      let text2 = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
      

      【讨论】:

        【解决方案5】:

        一个适合我的简单解决方案。更新,看起来我一定是从这里得到的,所以信用到期: Append text or data to text file in Swift

        用法:

        "Hello, world".appendToURL(fileURL: url)
        

        代码:

        extension String {
            func appendToURL(fileURL: URL) throws {
                let data = self.data(using: String.Encoding.utf8)!
                try data.append(fileURL: fileURL)
            }
        }
        
        extension Data {
            func append(fileURL: URL) throws {
                if let fileHandle = FileHandle(forWritingAtPath: fileURL.path) {
                    defer {
                        fileHandle.closeFile()
                    }
                    fileHandle.seekToEndOfFile()
                    fileHandle.write(self)
                }
                else {
                    try write(to: fileURL, options: .atomic)
                }
            }
        }    
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-04-24
          • 2013-10-17
          • 1970-01-01
          • 2017-12-13
          • 2014-02-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多