IOS File Handling
Introduction
File handling cannot be explained intuitively through an application; we can understand IOS file handling from the following examples.
File operations in IOS. Because the application is in a sandbox, file read/write permissions are restricted, and files can only be read/written in a few directories.
Methods Used in File Handling
The following is a list of methods used to access and manipulate files.
In the following examples you must replace the FilePath1, FilePath, and FilePath strings with complete file paths to obtain the desired operations.
Check whether the file exists
NSFileManager *fileManager = [NSFileManager defaultManager];
//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""]==YES) {
NSLog(@"File exists");
}
Compare the Contents of Two Files
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
NSLog(@"Same content");
}
Check Whether a File Is Writable, Readable, or Executable
if ([fileManager isWritableFileAtPath:@"FilePath"]) {
NSLog(@"isWritable");
}
if ([fileManager isReadableFileAtPath:@"FilePath"]) {
NSLog(@"isReadable");
}
if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
NSLog(@"is Executable");
}
Move files
if([fileManager moveItemAtPath:@"FilePath1"
toPath:@"FilePath2" error:NULL]){
NSLog(@"Moved successfully");
}
Copy a file
if ([fileManager copyItemAtPath:@"FilePath1"
toPath:@"FilePath2" error:NULL]) {
NSLog(@"Copied successfully");
}
Delete a file
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
NSLog(@"Removed successfully");
}
Reading a file
NSData *data = [fileManager contentsAtPath:@"Path"];
Writing to a File
[fileManager createFileAtPath:@"" contents:data attributes:nil];