开发者

How to read a file in iPhone?

I am t开发者_StackOverflow社区rying 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...


Use NSString's stringWithContentsOfFile: method.

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


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


Hopefully this is what you're after :

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

I usually have it looking in the Applications Document directory.


Hope this helps...

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

hAPPY cODING...


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!!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜