2012-08-16 100 views
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]; 

} 

回答

-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]; 
    } 
} 
+0

你的意思只是把字符串,並添加到它的結尾? – 2012-08-16 04:56:05

+0

你嘗試通過給你的字符串方法 – 2012-08-16 04:57:02

+0

這段代碼我試過這段代碼,它的工作原理,但它不會永久保存更改?任何其他建議?謝謝 – 2012-08-16 05:10:01

4

您需要NSFileHandle

NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:fileName]; 
[fileHandle seekToEndOfFile]; 
[fileHandle writeData:[content dataUsingEncoding:NSUTF8StringEncoding]]; 
+0

能否請您提供如何將這種融入我的代碼的例子嗎?謝謝 – 2012-08-16 04:55:02

+0

只是簡單地替換「[content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];」當代碼在 – 2012-08-16 05:01:20

+0

以上時,我會立即嘗試並報告回來。謝謝 – 2012-08-16 05:12:05