Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load text file from specific location objective c

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.

like image 230
Bushes Avatar asked Dec 03 '11 15:12

Bushes


1 Answers

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".

like image 68
syclonefx Avatar answered Sep 20 '22 17:09

syclonefx