iOS file processing


IOS file processing


Introduction

File processing cannot be explained intuitively through applications. We can learn about IOS file processing from the following examples.

Operations on files in IOS. Because the application is in a sandbox, it is restricted in file read and write permissions and can only read and write files 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 the full file path to obtain the desired operation.

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 the file is writable, readable, and executable

  if ([fileManager isWritableFileAtPath:@"FilePath"]) {      NSLog(@"isWritable");   }   if ([fileManager isReadableFileAtPath:@"FilePath"]) {      NSLog(@"isReadable");   }   if ( [fileManager isExecutableFileAtPath:@"FilePath"]){      NSLog(@"is Executable");   }

Move the 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];