如何将不同行中的String写入iOS上的.txt文件

时间:2013-04-06 09:45:04

标签: ios objective-c xcode string writetofile

我正在尝试将字符串写入应用程序的documents文件夹中的t.t文件。我可以将字符串写入其中,但是当我将另一个字符串写入文件时会覆盖另一个字符串,是否可以在文本文件中写入更多字符串,字符串之间有一个空行,这个字符串很多

字符串

字符串

斯特林

...

我正在使用此代码将字符串写入文本文件,它适用于一个字符串,但不适用于多字符串。

NSArray *paths = NSSearchPathForDirectoriesInDomains
        (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];

        //make a file name to write the data to using the documents directory:
        NSString *fileName = [NSString stringWithFormat:@"%@/Barcodedata.txt",
                              documentsDirectory];
        //create content - four lines of text
        NSString *content = [NSString stringWithFormat:@"%@",sym.data];
        //save content to the documents directory
        [content writeToFile:fileName
                  atomically:NO
                    encoding:NSStringEncodingConversionAllowLossy
                       error:nil];

1 个答案:

答案 0 :(得分:2)

有几种方法可以执行此操作,具体取决于您实现代码的方式。

一种方法是将原始的.txt文件加载到NSMutableString对象中,然后将该新行添加到字符串的末尾并重新写出文件(这不是超级高效的,尤其是在您启动时追加1000个字符串,100个字符串,50个字符串等。)

或者您可以使用低级别C函数“fwrite”并设置a ppend位。

编辑:

既然您想查看代码,请按照我的第一个建议执行此操作:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/Barcodedata.txt", documentsDirectory];
//create content - four lines of text

NSError * error = NULL;
NSStringEncoding encoding;
NSMutableString * content = [[NSMutableString alloc] initWithContentsOfFile: fileName usedEncoding: &encoding error: &error];
if(content == NULL)
{
    // if the file doesn't exist yet, we create a mutable string
    content = [[NSMutableString alloc] init];
}

if(content)
{
    [content appendFormat: @"%@", sym.data];

    //save content to the documents directory
    BOOL success = [content writeToFile:fileName
                            atomically:NO
                              encoding:NSStringEncodingConversionAllowLossy
                                 error:&error];

    if(success == NO)
    {
        NSLog( @"couldn't write out file to %@, error is %@", fileName, [error localizedDescription]);
    }
}
相关问题