栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何打开文件并在其中添加字符串,快速

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何打开文件并在其中添加字符串,快速

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

OutputStream
。例如:

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 textn"    let bytesWritten = outputStream.write(text)    if bytesWritten < 0 { print("write failure") }    outputStream.close()} else {    print("Unable to open file")}

顺便说一句,这是一个扩展,可以让你轻松地编写

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

或者,在 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")}

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/613953.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号