简体   繁体   中英

How Can i get data from the file in the documents folder

i am new to xcode and objective c.

firstly i have created a file in documents directory and it is created and now what i need is how can i read the data from that file like whether the file is containing a particular string or not

How can i get that

You can follow my answer here, saving and retrieving plist files

Array from File in XCode

Following method will get the contents of the file to a string.

+ (id)stringWithContentsOfFile:(NSString *)path
              usedEncoding:(NSStringEncoding *)enc
                     error:(NSError **)error

You can then find out if the returned string contains specified substring by:

NSRange textRange;
textRange =[string rangeOfString:@"ohai"];

if(textRange.location != NSNotFound) {

    //String contains substring "ohai"
}

Hope this helps.

the same way as you write you can retrieve the data , lets assume you want to get an image from your documents folder then see this code -

NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES)objectAtIndex:0]];
NSString *fileName = [stringPath stringByAppendingFormat:@"/image.jpg"];

//fileName is your image path and image.jpg is your image name which is saved in documents folder...
NSData *retrieveData = [NSData dataWithContentsOfFile:fileName];
UIImage *newImage = [UIImage imageWithData: retrieveData];

in this case instead of

[data writeToFile:fileName atomically:YES]; 

you have to write

NSData *retrieveData = [NSData dataWithContentsOfFile:fileName];

line. And you can get all kind of data.

Thank You!!

You can read data from file in documents folder in following way:

 NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/<pathofFile>"];
 NSString *fileContent = [[NSString alloc] initWithContentOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

Now, you can use NSString methods for searching substring in the fileContent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM