//Clear content of file
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"readFile Path : %@ ",paths);
documentsDirectory = [paths objectAtIndex:0];
appFile = [documentsDirectory stringByAppendingPathComponent:@"File.txt"];
fileManager=[NSFileManager defaultManager];
NSFileHandle *file;
file = [NSFileHandle fileHandleForUpdatingAtPath: appFile];
if (file == nil)
NSLog(@"Failed to open file");
[file truncateFileAtOffset:0];
[file closeFile];
//Method to invoke writeFile
[(AppDelegate *)[[UIApplication sharedApplication]delegate]
writeFile:@"DeptListFile.txt" data:newFileString];
// Method to Write in file
-(void)writeFile:(NSString *)fileName data:(id)data {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"writeFile Path : %@ ",paths);
documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirectory : %@ ",documentsDirectory);
appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(@"documentsDirectory : %@ ",documentsDirectory);
NSError *error=NULL;
fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile]) {
NSString *fileString=[NSString stringWithContentsOfFile:appFile
encoding:NSUTF8StringEncoding error:&error];
data=[data stringByAppendingFormat:@"\n%@",fileString];
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
else {
[data writeToFile:appFile atomically:YES encoding:NSUTF8StringEncoding error:&error];
}
if (error != NULL) {
//Check Error Here. if any.
}
}
// Code to read from file
NSString *fileText = [self readFile:@"File.txt"];
NSLog(@"File content : %@ ",fileText);
// Read from file
-(NSString *)readFile:(NSString *)fileName {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSLog(@"readFile Path : %@ ",paths);
documentsDirectory = [paths objectAtIndex:0];
NSLog(@"documentsDirectory : %@ ",documentsDirectory);
appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
NSLog(@"appFile : %@ ",appFile);
fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:appFile]) {
NSError *error= NULL;
id resultData=[NSString stringWithContentsOfFile:appFile encoding:NSUTF8StringEncoding
error:&error];
if (error == NULL) {
return resultData;
}
}
return NULL;
}
No comments:
Post a Comment