2009-09-29 21 views

回答

136

文件可以在您“在这条道路进入一个NSString的文件资源文件夹“实际上是您的应用程序包的内容。所以首先你需要在应用程序包中获取文件的路径。

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

然后将内容加载到NSString甚至更​​容易。

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

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

+0

编码不适用于所有文件。如果您在Windows中使用ANSI编码在欧元符号中创建文本文件,则使用上述代码将欧元符号转换为其他符号。有没有任何通用的方法来支持使用单一编码的所有字符集。 – 2015-04-01 17:23:08

8

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

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

然后你就可以直接读取使用initWithContentsOfFile:usedEncoding:error:

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