NSFileHandle
1.NSFileManager类主要对于文件的操作(删除,修改,移动,赋值等等)
NSFileManager *fileManage = [NSFileManager defaultManager];
BOOL success = [fileManage createFileAtPath:tagetPath contents:nil attributes:nil];
if (success) {
NSLog(@"create success");
}
2.NSFileHandle类主要对文件的内容进行读取和写入操作
①NSFileHandle处理文件的步骤
1:创建一个NSFileHandle对象
NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:srcPath];
NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];
2:对打开的文件进行I/O操作
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/Date.text"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
[fileHandle seekToEndOfFile];
[fileHandle seekToFileOffset:100];
NSString *str = @"add world";
NSData *stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:stringData];
3:关闭文件对象操作
[fileHandle closeFile];
常用处理方法,读
void readByFile(){
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSInteger length = [fileHandle availableData].length;
[fileHandle seekToFileOffset:length/2];
NSData *data = [fileHandle readDataToEndOfFile];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
[fileHandle closeFile];
}
复制文件
void copy2Other(){
NSString *homePath = NSHomeDirectory();
NSString *filePath = [homePath stringByAppendingPathComponent:@"phone/cellPhone.text"];
NSString *tagetPath = [homePath stringByAppendingPathComponent:@"phone/cellPhone_bak.text"];
NSFileManager *fileManage =[NSFileManager defaultManager];
BOOL success = [fileManage createFileAtPath:tagetPath contents:nil attributes:nil];
if (success) {
NSLog(@"create success");
}
NSFileHandle *outFileHandle = [NSFileHandle fileHandleForWritingAtPath:tagetPath];
NSFileHandle *inFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
NSData *data = [inFileHandle readDataToEndOfFile];
[outFileHandle writeData:data];
[inFileHandle closeFile];
[outFileHandle closeFile];
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步