在现有的txt文件-iOS上添加字符串

时间:2012-10-01 23:21:17

标签: ios nsdocument

如下面的代码所示,它输出了几个单独的.txt文件。但是,我正在寻找将所有内容保存到一个txt文件中的方法。如何在保存的txt文件末尾添加新字符串?

-(void)saveData:(NSString *)data
{

    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory=[paths objectAtIndex:0];
    NSString *fileName=[NSString stringWithFormat:@"%@/%d.txt",documentDirectory,fileInt];
    NSString *content=data;
    [content writeToFile:fileName atomically:NO encoding:NSStringEncodingConversionAllowLossy error:nil];
    NSLog(@"%@",fileName);
    fileInt++;
}

1 个答案:

答案 0 :(得分:3)

好的,我想我明白了。

-(void)saveData:(NSString*)data
{
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentDirectory=[paths objectAtIndex:0];
        NSString *fileName=[NSString stringWithFormat:@"%@/%d.txt",documentDirectory,1];
        NSString *content=data;
        NSFileHandle *fileHandler= [NSFileHandle fileHandleForWritingAtPath:fileName];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:[content dataUsingEncoding:NSUTF8StringEncoding]];
        [fileHandler closeFile];
        NSLog(@"%@",fileName);
}