以编程方式使用Objective-C读取文本文件

我是iPhone编程新手

我想读取我的资源文件夹中的文本文件的内容。 我做了很多search,但没有得到正确的方法来完成这项任务。

请build议

“资源文件夹”中的文件实际上是应用程序包的内容。 所以首先你需要在应用程序包中获取文件的path。

NSString* path = [[NSBundle mainBundle] pathForResource:@"filename" ofType:@"txt"]; 

然后将内容加载到NSString中更加容易。

 NSString* content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; 

作为一个奖励,你可以有不同的本地化版本的filename.txt ,这段代码将正确地获取当前所选语言的文件。

你想要做的第一件事就是获取你想要阅读的文本文件的path。 由于它在您的资源文件夹中,我假设您将其复制到应用程序的主包中。 您可以使用NSBundle的pathForResource:ofType:主包中文件的pathpathForResource:ofType:

 NSBundle *mainBundle = [NSBundle mainBundle]; NSString *filePath = [mainBundle pathForResource:@"filename" ofType:@"txt"]; 

然后,您可以直接使用initWithContentsOfFile:usedEncoding:error:将该path中的文件读入NSString initWithContentsOfFile:usedEncoding:error:

 NSStringEncoding encoding; NSError *error; NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:filePath usedEncoding:&encoding error:&error] autorelease];