如何打开文件并在其中附加一个字符串,swift [英] How to open file and append a string in it, swift
本文介绍了如何打开文件并在其中附加一个字符串,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.
推荐答案
如果您想控制是否追加,请考虑使用的OutputStream
。例如:
If you want to be able to control whether to append or not, consider using OutputStream
. For example:
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")
}
顺便说一句,这是一个扩展程序,可让您轻松编写字符串
到 OutputStream
:
By the way, this is an extension that lets you easily write a String
to an 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
}
}
这篇关于如何打开文件并在其中附加一个字符串,swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文