简体   繁体   English

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

[英]How to open file and append a string in it, swift

I am trying to append a string into text file.我正在尝试将字符串附加到文本文件中。 I am using the following code.我正在使用以下代码。

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
}

this does not append the string to file.这不会将字符串附加到文件。 Even if I call this function repeatedly.即使我反复调用这个函数。

If you want to be able to control whether to append or not, consider using OutputStream .如果您希望能够控制是否追加,请考虑使用OutputStream For example:例如:

SWIFT 3斯威夫特 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")
}

By the way, this is an extension that lets you easily write a String to an OutputStream :顺便说一句,这是一个扩展,可以让您轻松地将String写入OutputStream

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
    }

}

Or, in Swift 2 use NSOutputStream :或者,在Swift 2 中使用NSOutputStream

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")
}

And

extension NSOutputStream {

    /// Write `String` to `NSOutputStream`
    ///
    /// - parameter string:                The string to write.
    /// - parameter encoding:              The NSStringEncoding 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: NSStringEncoding = NSUTF8StringEncoding, allowLossyConversion: Bool = false) -> Int {
        if let data = string.dataUsingEncoding(encoding, allowLossyConversion: allowLossyConversion) {
            var bytes = UnsafePointer<UInt8>(data.bytes)
            var bytesRemaining = data.length
            var totalBytesWritten = 0

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

                bytesRemaining -= bytesWritten
                bytes += bytesWritten
                totalBytesWritten += bytesWritten
            }

            return totalBytesWritten
        }

        return -1
    }

}

You can also useFileHandle to append String to your text file.您还可以使用FileHandle将 String 附加到您的文本文件。 If you just want to append your string the end of your text file just callseekToEndOfFile method, write your string data and just close it when you are done:如果您只想将字符串附加到文本文件的末尾,只需调用seekToEndOfFile方法,写入字符串数据并在完成后关闭它:


FileHandle usage Swift 3 or Later 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)
}

Please check the below code as its working for me.请检查下面的代码,因为它对我有用。 Just Add the code as it is:只需按原样添加代码:

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)
        }
    }

Check the reading part.检查阅读部分。

The method cotentsOfFile: is a method of NSString class.方法cotentsOfFile:NSString类的方法。 And you have use it wrong way.你用错了方法。

So replace this line所以更换这一行

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

Here you have to use NSString instead of String class.在这里你必须使用NSString而不是String类。

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

A simple solution that works for me.一个对我有用的简单解决方案。 UPDATE, it looks like I must have gotten this from here, so credit where credit is due: Append text or data to text file in Swift更新,看起来我一定是从这里得到的,所以功劳应该归功于: 在 Swift 中将文本或数据附加到文本文件

Usage:用法:

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

Code:代码:

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)
        }
    }
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM