我是 iPhone 编程的新手。我想读取位于资源文件夹子文件夹中的文本文件的内容。
资源文件夹结构如下:
资源
- 文件夹1---->Data.txt
- 文件夹2---->Data.txt
- 文件夹3---->文件夹1---->Data.txt
有多个名为“Data.txt”的文件,那么如何访问每个文件夹中的文件?我知道如何读取文本文件,但是如果 Resource 结构与上述结构相似,那么我该如何获取路径?
例如,如果我想从 Folder3 访问“Data.txt”文件,如何获取文件路径?
请建议。
我是 iPhone 编程的新手。我想读取位于资源文件夹子文件夹中的文本文件的内容。
资源文件夹结构如下:
资源
有多个名为“Data.txt”的文件,那么如何访问每个文件夹中的文件?我知道如何读取文本文件,但是如果 Resource 结构与上述结构相似,那么我该如何获取路径?
例如,如果我想从 Folder3 访问“Data.txt”文件,如何获取文件路径?
请建议。
您的“资源文件夹”实际上是主包的内容,也称为应用程序包。您使用pathForResource:ofType:orpathForResource: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 上都可用。
要继续精神病学的回答,一个完整的例子如下所示:
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 访问子目录中的资源。
上面 Shirkrin 的回答和PeyloW 的回答都很有用,我设法使用它pathForResource:ofType:inDirectory:来访问我的应用程序包中不同文件夹中具有相同名称的文件。
我还在这里找到了一个更适合我的要求的替代解决方案,所以我想我会分享它。特别是,请参阅此链接。
例如,假设我有以下文件夹引用(蓝色图标,组为黄色):

然后我可以像这样访问图像文件:
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];
这为您提供了包的路径。从那里开始,您可以浏览您的文件夹结构。