2009-09-30 173 views
9

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

资源文件夹结构如下:

资源

  1. Folder1中----> DATA.TXT
  2. FOLDER2 ----> DATA.TXT
  3. Folder3-- - > Folder1 ----> Data.txt

有多个名为“Data.txt”的文件,所以如何访问每个文件夹中的文件?我知道如何阅读文本文件,但是如果资源结构与上述结构类似,那我该如何获得路径?

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

请建议。

回答

12

要继续psychotiks回答一个完整的例子是这样的:

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访问子目录ressources。

+0

但在不同的文件夹中有多个具有相同名称的文件夹。所以在这种情况下,如何实现路径 – Rupesh 2009-09-30 08:32:06

+4

@Rupesh:对于您需要使用的第二个文件夹:'[thisBundle pathForResource:@“Data”ofType:@“txt”inDirectory:@“Folder3/Folder1”]'。注意'inDirectory:'参数是相对于捆绑根目录的。 – PeyloW 2009-09-30 08:53:12

+1

你应该真的使用'[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL]',这样内存就是_“managed”_,更重要的是''initWithContentsOfFile:'从Mac OS X 10.4开始已经被弃用了,**可在iPhone OS **上使用。所以代码只能在模拟器中工作。 – PeyloW 2009-09-30 08:58:16

4
NSBundle* bundle = [NSBundle mainBundle]; 
    NSString* path = [bundle bundlePath]; 

这可以为您提供捆绑的路径。从那里开始,你可以导航你的文件夹结构。

16

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

如果您想保留一个字符串,则以stringWithContentsOfFile:encoding:error:方法将一个文件的内容作为字符串加载,该方法对于自动释放的字符串为initWithContentsOfFile:encoding:error:

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

7

Shirkrin's answerPeyloW's answer上面都是有用的,我设法使用pathForResource:ofType:inDirectory:访问我的应用程序包中不同文件夹中具有相同名称的文件。

我还发现了一个替代解决方案here,它适合我的要求略好,所以我想我会分享它。具体见this link

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

enter image description here

然后我就可以访问该图像文件是这样的:

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/"]; 
+0

谢谢。工作正常 – 2016-03-15 12:28:45

相关问题