Objective-C文件处理

使用NSFileManager类可以进行文件处理,这些示例不适用于在线编译器。

文件处理中使用的方法

下面列出了用于访问和操作文件的方法列表。 在这里,必须将FilePath1FilePath2FilePath字符串替换为所需的完整文件路径,以获得所需的操作。

1. 检查文件是否存在于路径中

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

2. 比较两个文件内容

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

3. 检查是否可写,可读和可执行

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

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

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

4. 移动文件

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

5. 复制文件

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

6. 删除文件

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

7. 读取文件

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

8. 写入文件

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

前面已成功学习了各种文件访问和操作技术,现在你应该对文件进行各种操作以及文件的使用所有了解。


上一篇: Objective_C基础框架 下一篇: Objective-C快速枚举