Last active
July 6, 2018 02:57
-
-
Save SongJiaqiang/47e1d31a515599300ff0071bbd1e945e to your computer and use it in GitHub Desktop.
在文件后面追加字符串
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func appendStringToFile() { | |
let dir:NSURL = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.CachesDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL | |
let fileurl = dir.URLByAppendingPathComponent("file.txt") | |
let string = "\(NSDate())\n" | |
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)! | |
if NSFileManager.defaultManager().fileExistsAtPath(fileurl.path!) { | |
var error:NSError? | |
if let fileHandle = NSFileHandle(forWritingToURL: fileurl, error: &error) { | |
fileHandle.seekToEndOfFile() | |
fileHandle.writeData(data) | |
fileHandle.closeFile() | |
} | |
else { | |
println("Can't open fileHandle \(error)") | |
} | |
} | |
else { | |
var error:NSError? | |
if !data.writeToURL(fileurl, options: .DataWritingAtomic, error: &error) { | |
println("Can't write \(error)") | |
} | |
} | |
} | |
func writeToFile(content: String, fileName: String) { | |
let contentToAppend = content+"\n" | |
let filePath = NSHomeDirectory() + "/Documents/" + fileName | |
//Check if file exists | |
if let fileHandle = NSFileHandle(forWritingAtPath: filePath) { | |
//Append to file | |
fileHandle.seekToEndOfFile() | |
fileHandle.writeData(contentToAppend.dataUsingEncoding(NSUTF8StringEncoding)!) | |
} | |
else { | |
//Create new file | |
do { | |
try contentToAppend.writeToFile(filePath, atomically: true, encoding: NSUTF8StringEncoding) | |
} catch { | |
print("Error creating \(filePath)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment