iOS File Handling


Introduction

File handling cannot be explained directly through applications. We can understand iOS file handling through the following examples.

File operations in iOS. Because applications are in a sandbox, they are restricted in file read/write permissions and can only read and write files in a few directories.

Methods Used in File Handling

The following lists the methods used to access and manipulate files.

In the following examples, you must replace the FilePath1, FilePath, and FilePath strings with full file paths to achieve the desired operations.

Check if 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 the 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 file

   if([fileManager moveItemAtPath:@"FilePath1" 
   toPath:@"FilePath2" error:NULL]){
      NSLog(@"Moved successfully");
   }

Copy file

   if ([fileManager copyItemAtPath:@"FilePath1" 
   toPath:@"FilePath2"  error:NULL]) {
      NSLog(@"Copied successfully");
   }

Delete file

 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
      NSLog(@"Removed successfully");
   }
 

Read file

 NSData *data = [fileManager contentsAtPath:@"Path"];
 

Write file

  [fileManager createFileAtPath:@"" contents:data attributes:nil];
Other extensions