ios - iPhone : Get the file path which is within subfolder of Resource folder

标签 ios cocoa-touch file path nsbundle

我是 iPhone 编程新手。我想读取位于 Resource 文件夹子文件夹中的文本文件的内容。

资源文件夹结构如下:

资源

  1. 文件夹1---->Data.txt
  2. 文件夹2---->Data.txt
  3. 文件夹3---->文件夹1---->Data.txt

有多个名为“Data.txt”的文件,如何访问每个文件夹中的文件?我知道如何读取文本文件,但是如果 Resource 结构类似于上面的结构,那么我如何获取路径?

比如我要访问Folder3中的“Data.txt”文件,如何获取文件路径?

请提出建议。

最佳答案

您的“资源文件夹” 实际上是主包的内容,也称为应用程序包。您可以使用 pathForResource:ofType:pathForResource:ofType:inDirectory: 获取资源的完整路径。

将文件的内容作为字符串加载是使用 stringWithContentsOfFile:encoding:error: 方法为自动释放的字符串完成的 with initWithContentsOfFile:encoding:error: if你想要一个保留的字符串。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Data" 
                                                     ofType:@"txt"
                                                inDirectory:@"Folder1"];
if (filePath != nil) {
  theContents = [NSString stringWithContentsOfFile:filePath
                                          encoding:NSUTF8StringEncoding
                                             error:NULL];
  // Do stuff to theContents
}

这与 Shirkrin 之前给出的答案几乎相同,但它在目标上的作用略有不同。这是因为 initWithContentsOfFile: 在 Mac OS X 上已弃用,并且并非在所有 iPhone OS 上都可用。

关于ios - iPhone : Get the file path which is within subfolder of Resource folder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1496373/

相关文章:

ios - Swift 变量在内存中丢失但在调试中可见

ios - indexpath 处行的高度不适用于自定义 uitableviewcell

linux - 将 grep 结果打印到文件和终端

performance - 前置到数GB的文件

JavaScript - 如何查看图像的原始数据

ios - 父旋转后获取 SpriteKit 节点的可见位置

ios - 无法在 iOS 应用程序中使用自定义字体

iphone - 如何让webview透明?

objective-c - iOS 多任务应用启动

objective-c - 检查 NSArray 中对象的重复属性值