0

我将文件写入应用程序的文档目录:

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

    // the path to write file
    NSString *file = [documentsDirectory stringByAppendingPathComponent:@"data.json"];

    [responseString writeToFile:file atomically:YES];

但是我怎样才能访问该文件?

我的代码如下所示:

NSString *filePath = [[NSFileManager defaultManager] pathForRessorce: @"data" ofType:@"JSON"];

    NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath]; 

    SBJsonParser *parser = [[SBJsonParser alloc] init];

    NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil];

文件路径未填充...有人可以给我一个提示吗?

谢谢!

4

2 回答 2

7

您正在从资源文件夹中读取,而不是从文档目录中读取。您需要以filePath与写作期间相同的方式进行填充。那是:

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

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.json"];
NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];
于 2012-08-03T15:22:49.220 回答
2

“initwithcontentsofffile 已弃用”警告

所以而不是:

NSString *fileContent = [[NSString alloc] initWithContentsOfFile:filePath];

利用:

NSString *userInfoFileContent = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
于 2014-08-17T09:06:55.423 回答