9.35.1. Brief introduction ¶
File processing can not be explained intuitively through the application, we can understand the file processing of IOS from the following examples.
The operation of files in IOS. Because the application is in the sandbox, the access to read and write to the file is restricted, and you can only read and write the file in several directories.
9.35.2. Methods used in file processing ¶
The following is a list of methods used to access and manipulate files.
In the following example you must replace the FilePath1, FilePath, and FilePath strings with the full file path to get 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 for writable, readable, and executable files
if ([fileManager isWritableFileAtPath:@"FilePath"]) {
NSLog(@"isWritable");
}
if ([fileManager isReadableFileAtPath:@"FilePath"]) {
NSLog(@"isReadable");
}
if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
NSLog(@"is Executable");
}
Move Fil
if([fileManager moveItemAtPath:@"FilePath1"
toPath:@"FilePath2" error:NULL]){
NSLog(@"Moved successfully");
}
Copy a file
if ([fileManager copyItemAtPath:@"FilePath1"
toPath:@"FilePath2" error:NULL]) {
NSLog(@"Copied successfully");
}
Delete a file
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
NSLog(@"Removed successfully");
}
Read a file
NSData *data = [fileManager contentsAtPath:@"Path"];
Write to a file
[fileManager createFileAtPath:@"" contents:data attributes:nil];