麻烦阅读文本文件

时间:2014-02-25 23:19:28

标签: ios objective-c

我在阅读应用中的txt文件时遇到了麻烦。我能够写文件,但我无法阅读我刚刚写的文件。所以我搜索了一些教程并决定创建一个单独的示例。但它仍无效。

以下是我正在使用的代码:

- (IBAction)gerarArquivo:(id)sender {
NSString *resultLine = [NSString stringWithFormat:@"%@,%@\n",@"teste1",@"teste2"];

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];

NSString *surveys = [docPath stringByAppendingPathComponent:@"results.csv"];

if (![[NSFileManager defaultManager] fileExistsAtPath:surveys]) {
    [[NSFileManager defaultManager] createFileAtPath:surveys contents:nil attributes:nil];
}

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:surveys];
[fileHandle seekToEndOfFile];
[fileHandle writeData:[resultLine dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandle closeFile];

NSLog(@"Foi");


}

- (IBAction)recuperarArquivo:(id)sender {

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES)objectAtIndex:0];

NSString *surveys = [docPath stringByAppendingPathComponent:@"results.csv"];

if ([[NSFileManager defaultManager] fileExistsAtPath:@"/results.csv"])
{
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:surveys];

    NSString *surveyResults = [[NSString alloc]initWithData:[fileHandle availableData] encoding:NSUTF8StringEncoding];
    [fileHandle closeFile];
    NSLog(surveyResults);

}

}

1 个答案:

答案 0 :(得分:3)

您的阅读代码包含if语句:

[[NSFileManager defaultManager] fileExistsAtPath:@"/results.csv"]

由于提供的路径(应该是fileExistsAtPath:surveys)不太可能工作,如果这不起作用,那么你将永远不会尝试读取文件内容。