Objective-C 文件处理
2016-08-05 09:56
405 查看
文件处理在 NSFileManager类的帮助下可实现大多数文件操作功能。
//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""]==YES) {
NSLog(@"File exists");
}
文件处理的方法
下面列出的方法用于访问和操作文件列表。在这里,我们必须替换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];
相关文章推荐
- objective-c 中随机数的用法 (3种:arc4random() 、random()、CCRANDOM_0_1() )
- 从Objective-C转战C++ Android平台开发实践(C++/Java)
- Objective-C 编译器
- Objective-C 学习笔记18 内存管理
- [Objective-c 基础 - 2.1] 封装
- Objective-C的block内存管理
- objective-c 编程总结 内存管理
- [Objective-c 基础 - 3.3] @property属性详解
- Objective-c 网络编程3 UIWebView 搜索框
- Objective-C 内存管理精髓
- Objective-C的setter和getter
- Objective-C instancetype关键字
- objective-c预处理
- 《objective-c基础教程》学习笔记(七)—— 存取方法
- objective-c延展类目协议
- Objective-c基础(二)-类的定义
- objective-C 协议的一点点领会
- Objective-C内存管理第五弹:自动释放池
- Objective-C对象之类对象和元类对象(一)
- 论坛源码推荐(11.6):iPhone6/6 plus屏幕适配Demo,Java代码转Objective-C