Handling Files in iOS

By | October 29, 2014

Hi All,

In Todays article we will see how we can handle files in Objective C.

The list of the methods used for accessing and manipulating files are listed below. Here you have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.

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");

Comparing two file contents

 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
         NSLog(@"Same content");

Check if writable, readable and executable

 if ([fileManager isWritableFileAtPath:@"FilePath"]) {
         NSLog(@"File isWritable");

  if ([fileManager isReadableFileAtPath:@"FilePath"]) {
          NSLog(@"File isReadable");

 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
          NSLog(@"File is Executable");

Move file

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

Copy file

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

Remove file

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

Read file

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

Write file

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

Leave a Reply

Your email address will not be published. Required fields are marked *