【问题标题】:Read Text file Programmatically using Objective-C使用 Objective-C 以编程方式读取文本文件
【发布时间】:2010-12-02 07:35:16
【问题描述】:

我是 iPhone 编程新手

我想阅读我的资源文件夹中的文本文件的内容。我做了很多谷歌搜索,但未能找到完成这项任务的正确方法。

请推荐

【问题讨论】:

    标签: iphone text file


    【解决方案1】:

    “资源文件夹” 中的文件实际上是应用程序包的内容。因此,首先您需要获取应用程序包中文件的路径。

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

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

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

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

    【讨论】:

    • 编码不适用于所有文件。如果您在 Windows 中使用 ANSI 编码创建包含欧元符号的文本文件,则欧元符号将使用上述代码转换为其他符号。有没有通用的方法来支持使用单一编码的所有字符集。
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多