Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

ios - iPhone : Get the file path which is within subfolder of Resource folder

I am new to iPhone programming. I want to read the content of a text file located in a subfolder of the Resource folder.

The Resource folder structure is the following:

Resource

  1. Folder1---->Data.txt
  2. Folder2---->Data.txt
  3. Folder3---->Folder1---->Data.txt

There are multiple files named "Data.txt", so how can I access the files in each folder? I know how to read the text file, but if the Resource structure is similar to the above structure then how can I get the path?

For example, if I want to access the "Data.txt" file from Folder3, how can I get the file path?

Please suggest.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your "resource folder" is actually the contents of your main bundle, also know as the application bundle. You use pathForResource:ofType: or pathForResource:ofType:inDirectory: to get the full path for a resource.

Loading the contents of a file as a string is done with the stringWithContentsOfFile:encoding:error: method for an autoreleased string of with initWithContentsOfFile:encoding:error: if you want a retained 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
}

This is almost the same answer as given by Shirkrin previously, but with the slight difference that it works on target. This is because initWithContentsOfFile: is deprecated on Mac OS X, and not available at all iPhone OS.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...