Rup*_*esh 9 cocoa-touch file path nsbundle ios
我是iPhone编程的新手.我想读取位于Resource文件夹的子文件夹中的文本文件的内容.
资源文件夹结构如下:
资源
有多个名为"Data.txt"的文件,那么如何访问每个文件夹中的文件?我知道如何阅读文本文件,但如果资源结构与上述结构类似,那么我该如何获取路径?
例如,如果我想从Folder3访问"Data.txt"文件,我该如何获取文件路径?
请建议.
Pey*_*loW 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
}
Run Code Online (Sandbox Code Playgroud)
这与Shirkrin先前给出的答案几乎相同,但它与目标有效的微小差别.这是因为initWithContentsOfFile:
在Mac OS X上已弃用,并且并非在所有iPhone OS上都可用.
Shi*_*rin 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
}
Run Code Online (Sandbox Code Playgroud)
请注意,您可以使用-pathForResource:ofType:inDirectory来访问子目录中的资源.
Shirkrin的回答和PeyloW上面的答案都很有用,我设法pathForResource:ofType:inDirectory:
用来访问我的应用程序包中不同文件夹中具有相同名称的文件.
我还在这里找到了一个替代解决方案,可以更好地满足我的要求,所以我想我会分享它.特别是,请看这个链接.
例如,假设我有以下文件夹参考(蓝色图标,组为黄色):
然后我可以像这样访问图像文件:
NSString * filePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"pin_images/1/2.jpg"];
UIImage * image = [UIImage imageWithContentsOfFile:filePath];
Run Code Online (Sandbox Code Playgroud)
作为旁注,pathForResource:ofType:inDirectory:
等效看起来像这样:
NSString * filePath = [[NSBundle mainBundle] pathForResource:@"2" ofType:@"jpg" inDirectory:@"pin_images/1/"];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
29443 次 |
最近记录: |