1

我已经设法写入一个文本文件,但我希望能够在不覆盖文本文件当前内容的情况下向文本文件添加更多数据。所以换句话说,我想每次都写到文件的末尾,这样它就不会删除当前的内容。以下代码是我到目前为止所做的,但它每次都会覆盖并写入开头,我不知道如何让它写入结尾。基于此代码,文本文件中的当前内容如下所示:

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];

 }
4

2 回答 2

4

你需要NSFileHandle

NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
于 2012-08-16T04:51:35.293 回答
1

使用此方法在文件末尾写入:

-(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];
  }
}
于 2012-08-16T04:53:32.203 回答