文件路径path,error:默认写nil
文件管理器 NSFlieManager :
主要是对 文件 进行 创建 删除 改名 等以及文件信息的获取 的操作
1、创建Manager
NSFileManager *fileManager = 【NSFileManager defaultManager】
2、创建一个文件并写入数据:
-(BOOL)createFileAtPath:(NSString*)path contents:(NSData*)data attributes:(NSDictionary*)dic;
3、从一个文件中读取数据
-(NSData*)contentsAtPath:(NSString*)path;
4、文件移动
-(BOOL)moveItemAtPath:(NSString*)srcPath toPath :(NSString*)dstPath error:(NSError*)error
5、文件的复制
-(Bool)copyItemAtPath:(NSString*)srcPath toPath:(NSString*)dstPath error:nil
6、比较两个文件的内容是否一样
-(BOOL)contentsEqualAtPath: path1 andPath:path2
7、文件是否存在
-(BOOL)fileExistsAtPath:path
8、移除文件
-(BOOL)removeItemAtPath:path error:nil
9、创建文件夹
-(BOOL)createDirectoryAtPath: path withIntermediateDirectory
文件连接器 NSFileHandle : 只能对内容修改,不能对文件
主要是对 文件内容 进行读取和写入的操作
三个类的方法,创建对用操作的handle:
1、读
+ (nullable instancetype)fileHandleForReadingAtPath:(NSString *)path;
还可以:
+ (nullable instancetype)fileHandleForReadingFromURL:(NSURL )url error:(NSError *)error
2、写
+ (nullable instancetype)fileHandleForWritingAtPath:(NSString *)path;
还可以:
+ (nullable instancetype)fileHandleForWritingToURL:(NSURL )url error:(NSError *)error
3、更新
+ (nullable instancetype)fileHandleForUpdatingAtPath:(NSString *)path;
还可以:
++ (nullable instancetype)fileHandleForUpdatingURL:(NSURL )url error:(NSError *)error
具体的一些:
1、返回可用的数据
-(NSData*)availableData;
2、从当前节点读到文件尾
-(NSData*)readDataToEndOfFlie;
3、从当前节点读到指定长度
-(NSData*)readDataOfLength:(NSUInteger)length;
4、写入数据
–writeData:(NSData*)data
5、获取当前文件的偏移量
-offsetInFile
6、跳到指定的文件偏移量
-seekToFileOffset: offset
7、跳到文件尾
seekToEndOfFile
8、将文件的长度设为offset字节
-truncateFileAtOffset:offset
具体代码:
//修改内容
NSFileHandle *filehandle=[NSFileHandle fileHandleForUpdatingAtPath:filePath];
//可以在一半的长度插入,但是后面的内容会被覆盖
//NSInteger len=[[filehandle availableData]length];
//[filehandle seekToFileOffset:len/2];
[filehandle seekToEndOfFile];
[filehandle writeData:[@"123" dataUsingEncoding:NSUTF8StringEncoding]];
[filehandle closeFile];
//定位数据
NSFileHandle *readFileHandle=[NSFileHandle fileHandleForReadingAtPath:filePath];
NSUInteger length=[[readFileHandle availableData] length];
[readFileHandle seekToFileOffset:length/2];
NSData *readData = [readFileHandle readDataToEndOfFile];
NSString *readStr=[[NSString alloc]initWithData:readData encoding:NSUTF8StringEncoding];
NSLog(@"%@",readStr);
[readFileHandle readDataOfLength:length];
//复制数据
//write 直接覆盖原来的
NSString *filePath2=[documentPath stringByAppendingPathComponent:@"file2.txt"];
[fileManager createFileAtPath:filePath2 contents:[@"hello" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSFileHandle *writeFileHandle=[NSFileHandle fileHandleForWritingAtPath:filePath2];
[writeFileHandle writeData: readData];
[writeFileHandle closeFile];