在objective-c中创建制表符分隔文件

时间:2011-10-13 19:06:19

标签: iphone objective-c nsfilemanager

我发现这个片段在线编写,然后将数据附加到文本文件中:

- (void)appendText:(NSString *)text toFile:(NSString *)filePath {

    // NSFileHandle won't create the file for us, so we need to check to make sure it exists
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) {

        // the file doesn't exist yet, so we can just write out the text using the 
        // NSString convenience method

        NSError *error = noErr;
        BOOL success = [text writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if (!success) {
            // handle the error
            NSLog(@"%@", error);
        }

    } 
    else {

        // the file already exists, so we should append the text to the end

        // get a handle to the file
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];

        // move to the end of the file
        [fileHandle seekToEndOfFile];

        // convert the string to an NSData object
        NSData *textData = [text dataUsingEncoding:NSUTF8StringEncoding];

        // write the data to the end of the file
        [fileHandle writeData:textData];

        // clean up
        [fileHandle closeFile];
    }
}

这对我有意义。我有一个具有3个属性的类,NSString,NSInteger和NSString。当我尝试使用这种方法时,我这样做:

for (MyObject *ref in array) {
    NSString *stringToFile = [NSString stringWithFormat:@"%@\t%i\t%@", ref.ChrID, ref.Position, ref.Sequence];
    [self appendText:stringToFile toFile:filePath];
}

看起来不太合适。我的数据如下:

NSString *tab* NSInteger *single space* NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline 
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
NSStringNSString *tab* NSInteger newline
...

我不确定是什么让它看起来像这样。当我NSLog数据时,它看起来很好。但第一行的东西搞砸了,然后一切似乎都没了。有什么想法吗?感谢。

1 个答案:

答案 0 :(得分:1)

方法appendText有几个问题:

  • 如果文件不存在,则使用NSString writeToFile方法编写第一行,而不使用\ n

  • 以下行使用NSData writeData方法

  • 编写
  • 使用文件管理器来检查存在,获取文件句柄,搜索EOF然后只写一行,省略关闭是非常低效的。并在以下每一行重复此操作。

这样做更好:

  • 获取用于写入的文件句柄,如果它还没有,它将被创建

  • 寻求EOF

  • 使用每行的writeData进行循环

  • 关闭文件

相关问题