NSFileManager和NSFileHandle使用

一、NSFileManager:
1.1、获取NSFileManager
NSFileManager *manager = [NSFileManager defaultManager];     NSFileManager是单例模式,所以不能使用alloc+init创建  
 

1.2、文件操作

NSString *filePath = [homePath stringByAppendingPathComponent:@"Documents/file.text"];  //创建路径
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];   编码数据
BOOL sucess = [manager createFileAtPath:filePath contents:data attributes:nil]; 创建文件,参数:文件路径、文件内容、文件的属性
NSData *datas = [manager contentsAtPath:filePath];  根据路径读取文件
NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];   将文件数据转换成string
BOOL sucess2 = [manager moveItemAtPath:filePath toPath:targetPath error:nil]  移动文件,移动的同时可以重命名文件名
BOOL sucess3 = [manager copyItemAtPath:filePath toPath:targetPath error:nil]; 复制文件
BOOL isExist = [manager fileExistsAtPath:filePath];//判断文件是否存在  
BOOL sucess4 = [manager removeItemAtPath:filePath error:nil];   删除文件
NSDictionary *dic = [manager attributesOfItemAtPath:filePath error:nil];  获取文件属性
BOOL success = [manager changeFileAttributes:attr atPath:path]                        更改文件的属性 
BOOL success = [manager isReadablefileAtPath:path] 测试文件是否存在,且是否能执行读操作 
BOOL success = [manager isWritablefileAtPath:path] 测试文件是否存在,且是否能执行写操作
 

1.3、目录操作

BOOL success1 = [manager createDirectoryAtPath:filePaths withIntermediateDirectories:YES attributes:nil error:&error]; 创建文件夹
-(NSString *)currentDirectoryPath                      获取当前目录 
-(BOOL)changeCurrentDirectoryPath:path                更改当前目录 
-(BOOL)copyPath:from toPath:to handler:handler      复制目录结构,to不能已经存在 
-(BOOL)createDirectoryAtPath:path attributes:attr    创建目录 
-(BOOL)fileExistsAtPath:path isDirectory:(BOOL *)flag       测试文件是否为目录 (flag存储结构yes/no) 
-(NSArray *)contentsOfDirectoryAtPath:path              列出目录的内容 
-(NSDirectoryEnumerator *)enumeratorAtPath:path  枚举目录的内容 
-(BOOL)removeFileAtPath:path handler:handler    删除空目录 
-(BOOL)movePath:from toPath:to handler:handler    重命名或移动一个目录,to不能是已经存在的 
 

二、NSFileHandle:

2.1 获取NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];    获取文件准备写入
                                   (NSFileHandle *)fileHandleForReadingAtPath:path                        打开一个文件准备读取
                                   (NSFileHandle *)fileHandleForUpdatingAtPath:path                        打开一个文件准备更新(读取和写入)
FileSize = [[attributes objectForKey:NSFileSize] intValue]    获取文件大小
[handle seekToEndOfFile]; 将游标链接到文件尾部
[handle writeData:data];    在尾部继续写入数据
[handle closeFile];   关闭文件
 
-(NSData *)readDataToEndOfFile                                            读取其余的数据直到文件末尾(最多UINT_MAX字节)
-(NSData *)readDataOfLength:(unsigned int)bytes 从文件读取指定数目bytes的内容
 
-(unsigned long long) offsetInFile      获取当前文件的偏移量
-(void)seekToFileOffset:offset         设置当前文件的偏移量 
-(unsigned long long) seekToEndOfFile      将当前文件的偏移量定位的文件末尾
-(void)truncateFileAtOffset:offset        将文件的长度设置为offset字节
 
 
原文地址:https://www.cnblogs.com/hepingqingfeng/p/5459115.html