使用 NSMutableString 附加到文件的末尾 [英] Appending to the end of a file with NSMutableString

查看:25
本文介绍了使用 NSMutableString 附加到文件的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日志文件,我正在尝试将数据附加到末尾.我有一个 NSMutableString textToWrite 变量,我正在执行以下操作:

I have a log file that I'm trying to append data to the end of. I have an NSMutableString textToWrite variable, and I am doing the following:

[textToWrite writeToFile:filepath atomically:YES 
                                    encoding: NSUnicodeStringEncoding error:&err];

但是,当我这样做时,文件中的所有文本都将替换为 textToWrite 中的文本.我怎样才能追加到文件的末尾?(或者更好的是,如何在文件末尾追加新行?)

However, when I do this all the text inside the file is replaced with the text in textToWrite. How can I instead append to the end of the file? (Or even better, how can I append to the end of the file on a new line?)

推荐答案

我猜你可以做几件事:

NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:aPath];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[textToWrite dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

请注意,这会将 NSData 附加到您的文件中——而不是 NSString.请注意,如果您使用 NSFileHandle,则必须事先确保该文件存在.如果路径中不存在文件,fileHandleForWritingAtPath 将返回 nil.请参阅 NSFileHandle 类参考.

Note that this will append NSData to your file -- NOT an NSString. Note that if you use NSFileHandle, you must make sure that the file exists before hand. fileHandleForWritingAtPath will return nil if no file exists at the path. See the NSFileHandle class reference.

或者你可以这样做:

NSString *contents = [NSString stringWithContentsOfFile:filepath];
contents = [contents stringByAppendingString:textToWrite];
[contents writeToFile:filepath atomically:YES encoding: NSUnicodeStringEncoding error:&err];

我相信第一种方法是最有效的,因为第二种方法涉及在将新内容写入文件之前将文件的内容读入 NSString.但是,如果您不希望您的文件包含 NSData 并希望将其保留为文本,则第二个选项将更适合您.

I believe the first approach would be the most efficient, since the second approach involves reading the contents of the file into an NSString before writing the new contents to the file. But, if you do not want your file to contain NSData and prefer to keep it text, the second option will be more suitable for you.

[更新]由于 stringWithContentsOfFile 已弃用 你可以修改第二种方法:

[Update] Since stringWithContentsOfFile is deprecated you can modify second approach:

NSError* error = nil;
NSString* contents = [NSString stringWithContentsOfFile:filepath
                                               encoding:NSUTF8StringEncoding
                                                  error:&error];
if(error) { // If error object was instantiated, handle it.
    NSLog(@"ERROR while loading from file: %@", error);
    // …
}
[contents writeToFile:filepath atomically:YES
                                 encoding:NSUnicodeStringEncoding
                                    error:&err];

查看有关stackoverflow的问题

这篇关于使用 NSMutableString 附加到文件的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆