iOS
iOS

Reputation: 3616

How to read a file in iPhone?

I am trying to read a .txt file from my documents directory in the form of NSString. Any idea how to read the file into NSString?

Thank you...

Upvotes: 4

Views: 5347

Answers (5)

Mandar Belkunde
Mandar Belkunde

Reputation: 924

I think this is the best way to read .txt file from DocumentDirectory.

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"txtFile.txt"];
    NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

I hope this will work for you!!

Upvotes: 0

Suresh Varma
Suresh Varma

Reputation: 9740

Hope this helps...

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,  YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileContents=[documentsDirectory stringByAppendingPathComponent:@"file.txt"];

hAPPY cODING...

Upvotes: 1

iOS
iOS

Reputation: 3616

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *myPathDocs =  [documentsDirectory stringByAppendingPathComponent:@"myfile.txt"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:myPathDocs])
    {
        NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        [fileManager copyItemAtPath:myPathInfo toPath:myPathDocs error:NULL];
    }       

    //Load from File
NSString *myString = [[NSString alloc] initWithContentsOfFile:myPathDocs encoding:NSUTF8StringEncoding error:NULL];

This worked for me

Anyway, thank you all..

Upvotes: 2

MDMonty
MDMonty

Reputation: 363

Hopefully this is what you're after :

NSString *myString  = [[NSString alloc] initWithContentsOfFile:@"pathToFile"];

I usually have it looking in the Applications Document directory.

Upvotes: 1

Jacob Relkin
Jacob Relkin

Reputation: 163228

Use NSString's stringWithContentsOfFile: method.

NSString *fileContents = [NSString stringWithContentsOfFile:@"some/file.txt"];

Upvotes: 4

Related Questions