iOS - File Handling

File managing cannot be described creatively with the program and hence the key methods that are used for managing information are described below. Note that the program package only has read authorization and we won’t be able to alter the information. You can anyway change the records directory of your program.

Methods used in File Handling

The techniques used for obtaining and adjusting the information are mentioned below. Here we have to substitute FilePath1, FilePath2 and FilePath post to our required full computer file routes to get the preferred action.

Check if a File Exists at a Path

   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(@"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");
   }

Remove 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];

1 comments :

Write comments
11 August 2020 at 23:07 delete

Very nice post,thank you for sharing this awesome blog with us.

ios online training

Reply
avatar