[英]About 2000 strings to a file
我需要将单独的行放入文件中,但似乎它不受支持
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"myFile"];
[dataString writeToFile:appFile atomically:YES];
它确实将一个字符串放到一个文件中,但它会覆盖前一个文件。
有什么建议么?
要将数据附加到现有文件,请为该文件创建NSFileHandle
实例,然后调用-seekToEndOfFile
,最后调用-writeData:
. 您必须自己将字符串转换为NSData
对象(使用正确的编码)。 并且不要忘记在完成后关闭文件句柄。
更简单但效率更低的方法是将现有文件内容读入字符串,然后将新文本附加到该字符串并再次将所有内容写入磁盘。 不过,我不会在执行2000次的循环中这样做。
谢谢Ole! 这就是我一直在寻找的东西。
其他的一些示例代码:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//creating a path
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"nameOfAFile"];
//clearing or creating (NSFileHande doesn't support creating a file it seems)
NSString *nothing = @""; //remember it's CLEARING! so get rid of it - if you want keep data
[nothing writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
//creating NSFileHandle and seeking for the end of file
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:appFile];
[fh seekToEndOfFile];
//appending data do the end of file
NSString *dataString = @"All the stuff you want to add to the end of file";
NSData *data = [dataString dataUsingEncoding:NSASCIIStringEncoding];
[fh writeData:data];
//memory and leaks
[fh closeFile];
[fh release];
[dataString release];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.