如何在文本文件的追加模式下编写

时间:2011-01-24 08:12:56

标签: iphone uitextview nsfilehandle

我的应用程序导航基础。 UItextView用于注释UIViewController。我正在写文本数据到文件。现在我需要写入追加模式,下面的代码我正在尝试,但每次都用相同的文本数据写入两次,如果下一个文本数据要文件,则不附加。

- (void)saveText:(id)sender
{
    [self.textview resignFirstResponder];
    NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [documentPaths objectAtIndex:0];
    NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
    NSString *savedString = textview.text;
    [savedString writeToFile:documentTXTPath atomically:YES];


    NSFileHandle *myHandle = [NSFileHandle fileHandleForUpdatingAtPath:documentTXTPath ];
    [myHandle seekToEndOfFile];
    [myHandle writeData:  [savedString dataUsingEncoding:NSUTF8StringEncoding]];
    [myHandle closeFile];

}

3 个答案:

答案 0 :(得分:32)

删除以下代码行

[savedString writeToFile:documentTXTPath atomically:YES];

剩下的代码都很好。无论如何也检查我的代码,

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
    NSString *savedString = textview.text;
    NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:documentTXTPath];
    [myHandle seekToEndOfFile];
    [myHandle writeData:[savedString dataUsingEncoding:NSUTF8StringEncoding]];

答案 1 :(得分:26)

试试这个效果很好

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.txt"];
NSString *savedString = textview.text;

如果文件不存在则创建它并写入文件,否则它已经创建后附加到文件末尾

NSFileManager *fileManager = [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:documentTXTPath])
{
  [savedString writeToFile:documentTXTPath atomically:YES];
}
else
{
  NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:documentTXTPath];
  [myHandle seekToEndOfFile];
  [myHandle writeData:[savedString dataUsingEncoding:NSUTF8StringEncoding]];
}

答案 2 :(得分:-1)

您也可以

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *documentTXTPath = [documentsDirectory stringByAppendingPathComponent:@"Notes.text"];
NSString *content = [NSString stringWithContentsOfFile:documentTXTPath encoding:NSUTF8StringEncoding error:nil];
content = [content stringByAppendingString:data];

再次将内容写入特定文件路径

[content writeToFile:documentTXTPath atomically:YES encoding:NSUTF8StringEncoding error:nil];