May 21, 2021 iOS Development Manual
File processing cannot be interpreted intuitively through the application, and we can learn about IOS file processing from the following examples.
Operations on files in IOS. Because the app is in a sandbox, there are restrictions on file read and write permissions, and you can only read and write files in several directories.
Below is a list of methods for accessing and operating files.
The following examples you must replace the FilePath1, FilePath, and FilePath strings with the full file path to get the action you need.
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 the two files
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) { NSLog(@"Same content"); }
Check for writeable, readable, and executable files
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 the file
if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) { NSLog(@"Copied successfully"); }
Delete the file
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) { NSLog(@"Removed successfully"); }
Read the file
NSData *data = [fileManager contentsAtPath:@"Path"];
Write to the file
[fileManager createFileAtPath:@"" contents:data attributes:nil];