Load text file from specific location objective c

12,399

Solution 1

If you want to read files from the app bundle and you want a certain directory structure, then you need to create a directory in Finder. Then create the directory structure you want in the main directory you just made. Now add the files to the appropriate folders and then add the main directory to your project by dragging it in to Xcode.

Here is the code to read from the main bundle:

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Text/1" ofType:@"txt"];
    NSString *testString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",testString); 

This will read the file "1.txt" from the directory "Text".

Solution 2

iOS application will save all file to root directory, a Group(yellow icon) not a real directory. If you want put your resources into a sub directory, can using this following steps:

  1. Create a directory in the Finder, put your files into this directory.
  2. In Xcode, select "Add Files to..." from File menu.
  3. Select "Copy items into destination group's folder" and "Create Folder References for any added folders" in the popup.

Then, you will found a blue icon directory in your project, It is a real directory.

Now, you can read the files use NSBundle Class method:

+ (NSArray *)pathsForResourcesOfType:(NSString *)extension inDirectory:(NSString *)bundlePath
Share:
12,399
Bushes
Author by

Bushes

Updated on June 19, 2022

Comments

  • Bushes
    Bushes almost 2 years

    I was wondering how to read a file from a specific location on ios.

    For example I'd quite like to have files of the same name stored in different locations for example.

    Project/Files/Text/1.txt

    Project/Files/MoreText/1.txt

    At the moment I can load files in but I can't see how to specify a specific directory. My program seems to load a file in regardless of where it is meaning I can only have one text file or the other working.

    I have tried using NSFileManager:

    NSFileManager *filemanager = [NSFileManager defaultManager];
    
    NSArray *filelist = [filemanager directoryContentsAtPath:@"Text"];
    

    but I later realised that this actually isn't doing anything. It just returns no objects. I've also seen NSBundle but haven't seen an example where a specific file is returned.

    I need the filenames to be the same for my algorithm which loads the files.

    Any help would be appreciated.

  • Bushes
    Bushes over 12 years
    I've tried as you suggested, I put the files in a separate folder in my project but when I add the files and do as you suggest it seems to make a copy of them in the base directory rather then use the files in the folder. What's going wrong?
  • Bushes
    Bushes over 12 years
    I should also say I'm using xCode 3 rather than 4.