iOS - 文件处理

文件处理无法通过应用程序直观地解释,因此用于处理文件的关键方法将在下面解释。 请注意,应用程序包只有读取权限,我们无法修改文件。 无论如何,您都可以修改应用程序的文档目录。


文件处理中使用的方法

用于访问操作文件的方法将在下面讨论。 在这里,我们必须将 FilePath1、FilePath2 和 FilePath 字符串替换为我们所需的完整文件路径才能获得所需的操作。


检查文件是否存在于某个路径

实例


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

比较两个文件内容

实例


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

检查是否可写、可读和可执行

实例


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

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

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

移动文件

实例


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

复制文件

实例


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

删除文件

实例


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

读取文件

实例


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

写入文件

实例


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