我已设法写入文本文件,但我希望能够在不覆盖文本文件的当前内容的情况下向文本文件添加更多数据。换句话说,我想每次都写到文件的末尾,所以它不会删除当前内容。下面的代码是我到目前为止所做的,但它每次都会覆盖并写入开头,我不知道如何将它写到最后。根据此代码,文本文件中的当前内容如下所示:
June
July
August
September
我希望能够添加以下内容,例如
June
July
August
September
October
有谁知道怎么做?谢谢!
-(void) writeToTextFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"June\nJuly\nAugust\nSeptember";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
答案 0 :(得分:4)
您需要NSFileHandle
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
答案 1 :(得分:0)
使用此方法在文件结尾处写入:
-(void) writeToTextFileWithString:(NSString *) content name:(NSString *) file {
//TODO: Disable logs at release time
content = [NSString stringWithFormat:@"%@ ||| %@\n",content,[[NSDate date] description]];
//get the documents directory:
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *fileName = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",file]];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
if (fileHandle){
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];
}
else{
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
}
}