NSFileManager

NSFileManager类主要对文件和目录的操作(删除、修改、移动、复制等等)。如果对文件的内容更改,应该使用NSFileHandle。所以说NSFileManager相对于NSFileHandle偏向于对文件的管理,而不是对内容的操作。

NSFileManager管理文件

1. 创建文件
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:@"text"];

if ([[NSFileManager defaultManager]createFileAtPath:filePath contents:nil attributes:nil]) {
    NSLog(@"文件创建成功");
}else{
    NSLog(@"文件创建失败");
}
2. 文本写入
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *filePath = [path stringByAppendingPathComponent:@"text.txt"];
NSString *message = @"hello";
[[NSFileManager defaultManager]createFileAtPath:filePath contents:[message dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES] attributes:nil];
3. 文本读取
NSData *data = [[NSFileManager defaultManager]contentsAtPath:filePath];
NSString *text = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
4. 移动文件路径
[[NSFileManager defaultManager]moveItemAtPath:oldPath toPath:newPath error:NULL];
5. 复制文件
[NSFileManager defaultManager]copyItemAtPath:path toPath:newPath error:NULL];
6. 比较两个文件的内容
- (BOOL)contentsEqualAtPath:(NSString *)path1 andPath:(NSString *)path2;
7. 文件是否存在
- (BOOL)fileExistsAtPath:(NSString *)path;
8. 删除文件
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **) error;
9. 获取文件大小

获得文件的属性字典 

 NSDictionary *attrDic = [[NSFileManager defaultManager] attributesOfItemAtpath:sourcePath error:nil];  
 NSNumber *fileSize = [attrDic objectForKey:NSFileSize];
10. 测试文件是否存在,且是否能执行读操作
  -BOOLisReadablefileAtPath:path
11. 测试文件是否存在,且是否能执行写操作
  -BOOLisWritablefileAtPath:path
附录: 用C语言获取文件的大小

int getFileSizeFromPath(char * path){ FILE * file; int fileSizeBytes = 0; file = fopen(path,"r"); if(file>0){ fseek(file, 0, SEEK_END); fileSizeBytes = ftell(file); fseek(file, 0, SEEK_SET); fclose(file); } return fileSizeBytes;}

NSFileManager管理目录

1. 获取当前目录
-(NSString *)currentDirectoryPath
2. 更改当前目录
-(BOOL)changeCurrentDirectoryPath:path
3. 复制目录结构,to不能已经存在
-(BOOL)copyPath:from toPath:to handler:handler
4. 创建目录
-(BOOL)createDirectoryAtPath:path attributes:attr
5. 测试文件是否为目录 (flag存储结构yes/no)
 -(BOOL)fileExistsAtPath:path isDirectory:(BOOL *)flag
6. 列出目录的内容
 -NSArray *)contentsOfDirectoryAtPath:path
7. 枚举目录的内容
 -(NSDirectoryEnumerator *)enumeratorAtPath:path
8. 删除空目录
 -(BOOL)removeFileAtPath:path handlerhandler
9. 重命名或移动一个目录,to不能是已经存在的
 -BOOLmovePath:from toPath:to handler:handler
文章转自: http://www.jianshu.com/p/186ccef700a9   Hi唐吉柯德
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值