我是 iPhone 编程新手。我想读取位于 Resource 文件夹子文件夹中的文本文件的内容。
资源文件夹结构如下:
资源
- 文件夹1---->Data.txt
- 文件夹2---->Data.txt
- 文件夹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/