因为接下来代码中会反复使用地址,所以先进行宏定义
#define kPath(subPath) [NSStringstringWithFormat:@"/Users/macbook/Documents/test/%@",subPath]一、使用NSFileManager创建文件目录
//NSFileManager创建目录 NSFileManager *fileManager = [NSFileManagerdefaultManager]; NSError *error = nil; BOOL ret = [fileManager createDirectoryAtPath:kPath(@"test1") withIntermediateDirectories:NO attributes:nilerror:&error]; if (ret) { NSLog(@"创建成功!"); }else{ NSLog(@"失败原因:%@",error); }
二、使用NSFileManager创建任意文件
//创建文件 NSString *string = @"文本操作"; NSData *data = [stringdataUsingEncoding:NSUTF8StringEncoding]; ret = [fileManagercreateFileAtPath:kPath(@"test.txt") contents:data attributes:nil]; if (ret) { NSLog(@"创建成功!"); }三、文件遍历操作
//浅度遍历(该方法返回值为数组,只展示当前目录下内容) NSArray *contents = [fileManagercontentsOfDirectoryAtPath:kPath(@"") error:nil]; NSLog(@"%@",contents); //深度遍历(会展示当前目录下的子目录内容) contents = [fileManagersubpathsOfDirectoryAtPath:kPath(@"") error:nil]; NSLog(@"%@",contents);四、文件移动复制删除操作
//移动文件(需看清楚提醒使用的是moveItemAtPath,要在目标路径后加上被移动文件名) [fileManagermoveItemAtPath:kPath(@"test.txt")toPath:kPath(@"test1/test.txt") error:nil]; //复制文件 [fileManager copyItemAtPath:kPath(@"test1/test.txt")toPath:kPath(@"") error:nil]; //删除文件 [fileManagerremoveItemAtPath:kPath(@"test1/test.txt") error:nil]; //查看文件属性(该方法返回值为字典类型,所以用字典接受返回值) NSDictionary *dic = [fileManagerattributesOfItemAtPath:kPath(@"test.txt") error:nil]; NSLog(@"文件属性:%@",dic);五、文件读写操作
//NSFileHandle读写文件操作 //只读方式打开 NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:kPath(@"test.txt") ]; //读写从光标开始读开始写 //光标开始位置到结尾,默认光标在文件最开始 NSLog(@"%@",[fileHandle readDataToEndOfFile]); //打开文件要关闭 [fileHandle closeFile]; //只写方式打开 //以只读方式打开再用读写方式打开再读数据会报错 fileHandle = [NSFileHandle fileHandleForWritingAtPath:kPath(@"test.txt")]; [fileHandle closeFile]; //更新方式打开 fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:kPath(@"test.txt")]; NSLog(@"%@",[fileHandle readDataToEndOfFile]); //光标会移动 //移动光标到最开始位置,0为最开始 [fileHandle seekToFileOffset:0]; NSLog(@"%@",[fileHandle readDataOfLength:3]); //写入字符串 NSString *string = @"update"; [fileHandle writeData:[string dataUsingEncoding:NSUTF8StringEncoding]]; //实现实时更新文件 [fileHandle synchronizeFile]; [fileHandle closeFile]; //读进来的是二进制字符串需要转换
新闻热点
疑难解答