Ios 如何打开文件并在其中附加字符串,swift

Ios 如何打开文件并在其中附加字符串,swift,ios,swift,Ios,Swift,我正在尝试将字符串附加到文本文件中。我正在使用以下代码 let dirs : [String]? = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] if (dirs) != nil { let dir = dirs![0] //documents directory

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

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
}

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

检查阅读部分

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

所以,换掉这条线

let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
这里您必须使用
NSString
而不是
String

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

如果您想控制是否附加,请考虑使用<代码> OutPoStuts。例如:

SWIFT 3

let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    .appendingPathComponent("votes.txt")

if let outputStream = OutputStream(url: fileURL, append: true) {
    outputStream.open()
    let text = "some text\n"
    let bytesWritten = outputStream.write(text)
    if bytesWritten < 0 { print("write failure") }
    outputStream.close()
} else {
    print("Unable to open file")
}
或者,在Swift 2中使用
NSOutputStream

extension OutputStream {

    /// 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`.
    ///
    /// - returns:                         Return total number of bytes written upon success. Return `-1` upon failure.

    func write(_ string: String, encoding: String.Encoding = .utf8, allowLossyConversion: Bool = false) -> Int {

        if let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) {
            return data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Int in
                var pointer = bytes
                var bytesRemaining = data.count
                var totalBytesWritten = 0

                while bytesRemaining > 0 {
                    let bytesWritten = self.write(pointer, maxLength: bytesRemaining)
                    if bytesWritten < 0 {
                        return -1
                    }

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

                return totalBytesWritten
            }
        }

        return -1
    }

}
let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
let path = documents.URLByAppendingPathComponent("votes").path!

if let outputStream = NSOutputStream(toFileAtPath: path, append: true) {
    outputStream.open()
    let text = "some text"
    outputStream.write(text)

    outputStream.close()
} else {
    print("Unable to open file")
}

扩展NSOutputStream{ ///将'String'写入'NSOutputStream'` /// ///-参数字符串:要写入的字符串。 ///-参数编码:写入字符串时使用的NSStringEncoding。默认为UTF8。 ///-参数allowLossyConversion:写入字符串时是否允许有损转换。默认为'false'。 /// ///-返回:返回成功时写入的总字节数。失败时返回-1。 func write(string:string,encoding:NSStringEncoding=NSUTF8StringEncoding,allowossyconversion:Bool=false)->Int{ 如果let data=string.dataUsingEncoding(编码,allowossyconversion:allowossyconversion){ var bytes=UnsafePointer(data.bytes) var byteslaining=data.length var TotalBytesWrited=0 而字节数剩余>0{ 让bytesWrite=self.write(字节,最大长度:剩余字节数) 如果字节数小于0{ 返回-1 } 字节剩余-=字节写入 字节+=字节写入 TotalBytesWrited+=BytesWrited } 返回TotalBytesWrited } 返回-1 } }
请检查以下代码,因为它对我有效。只需按原样添加代码:

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)
        }
    }
您还可以使用将字符串附加到文本文件中。如果您只想将字符串附加到文本文件的末尾,只需调用方法,编写字符串数据并在完成后将其关闭:


文件句柄使用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)
}

一个对我有效的简单解决方案。更新,看起来我一定是从这里得到了这个,所以信用到期的地方:

用法:

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


这个错误参数在某些情况下很有用。当我尝试使用
let text2=String(contentsOfFile:path,encoding:NSUTF8StringEncoding,error:nil)println(text2)
读取它提供给nil的文件时,在尝试
写入
之前,您是否确实打开了
NSOutputStream
?如果不这样做,
写入
将失败。另外,在再次尝试读取文件之前,您是否明确地
关闭了
NSOutputStream
?您必须先关闭该文件,然后再尝试使用它。如果仍然存在问题,请尝试检查
write
函数的返回值,看看是否成功。
write
函数要求我输入
maxLength
。我应该在那里放什么?是的,在分别写入和读取之前,我已经打开和关闭了
NSOutputStream
。您不应该有
maxLength
参数。这意味着您调用了错误的
write
函数格式副本。您是否在我的回答中包含了我提供的
扩展名
"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)
        }
    }
}