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

Rup*_*esh 60 iphone text file

我是iPhone编程的新手

我想阅读我的Resourse文件夹中的文本文件的内容.我做了很多谷歌搜索,但没有得到正确的方法来完成这项任务.

请建议

Pey*_*loW 146

在这些文件中的"资源文件夹"实际上是你的应用程序包的内容.首先,您需要在应用程序包中获取文件的路径.

NSString* path = [[NSBundle mainBundle] pathForResource:@"filename" 
                                                 ofType:@"txt"];
Run Code Online (Sandbox Code Playgroud)

然后将内容加载到一个NSString更容易.

NSString* content = [NSString stringWithContentsOfFile:path
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];
Run Code Online (Sandbox Code Playgroud)

作为奖励,您可以拥有不同的本地化版本,filename.txt此代码将正确获取当前所选语言的文件.


Tim*_*Tim 8

您要做的第一件事是获取您想要阅读的文本文件的路径.因为它在你的Resources文件夹中,所以我假设你将它复制到应用程序的主包中.您可以使用NSBundle获取主包中文件的路径pathForResource:ofType:

NSBundle *mainBundle = [NSBundle mainBundle];
NSString *filePath = [mainBundle pathForResource:@"filename" ofType:@"txt"];
Run Code Online (Sandbox Code Playgroud)

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

NSStringEncoding encoding;
NSError *error;
NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:filePath
                                                      usedEncoding:&encoding
                                                             error:&error]
                          autorelease];
Run Code Online (Sandbox Code Playgroud)