< Objective-C >文件操作-NSFileManager

NSFileManager主要负责创建与删除等操作

 

NSFileManager类主要方法

+(NSFileManager *)defaultManager;获得文件管理器对象
-(BOOL)createFileAtPath:(NSString *)path contents:(NSData *)data attributes:(NSDictionary *)attr;创建文件
-(BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error;创建目录
-(BOOL)fileExistsAtPath:(NSString *)path;判断一个文件或目录是否存在
-(BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;判断文件是否存在且判断path是文件还是目录
-(BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;文件或目录复制
-(BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error;文件或目录移动
-(BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error;文件或目录删除
 
 
创建文件代码
//创建文件
NSFileManager *fm = [NSFileManager defaultManager];  //创建文件管理器
        
NSString *path = @"/Users/ni/Desktop/input.txt";
NSString *str = @"Hello World!";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];  //将str转化为NSData类型
        
BOOL flag = [fm createFileAtPath:path contents:data attributes:nil];
if(flag) {
    NSLog(@"create success!");
} else {
    NSLog(@"create fail!");
}

读取文件代码

//读取文件
NSString *fileContent = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",fileContent);

NSData:用来设置缓冲区,将文件内容读入缓冲区,或将缓冲区的内容写到一个文件

 

 

目录(文件夹)操作:遍历方法
-(NSDirectoryEnumerator *)enumeratorAtPath:(NSString *)path;深度遍历(遍历所有子文件夹),返回目录枚举器(NSDirectoryEnumerator)
-(NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error;浅度遍历,返回目录中的所有文件&文件夹的名字

 

NSString *dirPath = @"/Users/ni/Desktop/workspace";
NSFileManager *fm = [NSFileManager defaultManager];

//深度遍历
NSDirectoryEnumerator *dirs = [fm enumeratorAtPath:dirPath];        
NSString *path = [dirs nextObject];
while (path != nil) {
    NSLog(@"%@",path);
    path = [dirs nextObject];
}
     
//浅度遍历   
NSArray *arr = [fm contentsOfDirectoryAtPath:dirPath error:nil];
NSLog(@"%@", arr);

NSDirectoryEnumerator类有两个方法
-(id)nextObject;
-(NSArray *)allObjects;

转载于:https://www.cnblogs.com/aY-Wonder/p/4562723.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值