iPhone:获取资源文件夹子文件夹内的文件path

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

资源文件夹结构如下所示:

资源

  1. 文件夹1 —-> DATA.TXT
  2. 文件夹2 —-> DATA.TXT
  3. Folder3 —-> —- Folder1中> DATA.TXT

有多个名为“Data.txt”的文件,所以如何访问每个文件夹中的文件? 我知道如何阅读文本文件,但如果资源结构类似于上述结构,那么我怎么能得到的path?

例如,如果我想从Folder3访问“Data.txt”文件,如何获取文件path?

请build议。

继续精神病学回答一个完整的例子将如下所示:

NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; NSString *filePath = nil; if (filePath = [thisBundle pathForResource:@"Data" ofType:@"txt" inDirectory:@"Folder1"]) { theContents = [[NSString alloc] initWithContentsOfFile:filePath]; // when completed, it is the developer's responsibility to release theContents } 

请注意,您可以使用-pathForResource:ofType:inDirectory来访问子目录中的资源。

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

stringWithContentsOfFile:encoding:error:加载文件的内容stringWithContentsOfFile:encoding:error: initWithContentsOfFile:encoding:error:的自动释放string的方法initWithContentsOfFile:encoding:error:如果你想保留一个string。

 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上都不可用。

Shirkrin的答案和上面的PeyloW的答案都是有用的,我设法使用pathForResource:ofType:inDirectory:来访问我的应用程序包中不同文件夹中具有相同名称的文件。

我还发现了一个更适合我的要求的替代解决scheme,所以我想我会分享它。 特别是看到这个链接 。

例如,说我有以下文件夹引用(蓝色图标,组是黄色的):

在这里输入图像说明

然后我可以像这样访问图像文件:

 NSString * filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"pin_images/1/2.jpg"]; UIImage * image = [UIImage imageWithContentsOfFile:filePath]; 

作为一个侧面说明, pathForResource:ofType:inDirectory:等价物看起来像这样:

 NSString * filePath = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"jpg" inDirectory:@"pin_images/1/"]; 
  NSBundle* bundle = [NSBundle mainBundle]; NSString* path = [bundle bundlePath]; 

这给你的path到你的包。 从那里,你可以导航你的文件夹结构。