获取Document在沙盒中的路径(NSDocumentDirectory:Document目录 NSLibraryDirectory:Library目录 NSCachesDirectory:Caches目录
)
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [documentPath objectAtIndex:0];
NSLog(@"documentDirectory=%@",documentDirectory);
NSFileManager *fileManager = [NSFileManager defaultManager];
//创建文件夹
NSString *testDirectory = [documentDirectory stringByAppendingPathComponent:@"test"];
[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
//创建文件
NSString *testFilePath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
[fileManager createFileAtPath:testFilePath contents:nil attributes:nil];
//写数据到文件
NSString *fileContent = @"测试!!!";
[fileContent writeToFile:testFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//读文件数据
NSString *content = [NSString stringWithContentsOfFile:testFilePath encoding:NSUTF8StringEncoding error:nil];
NSLog(@"content=%@",content);
//删除文件
[fileManager removeItemAtPath:testFilePath error:nil];
NSLog(@"文件是否存在:%@", [fileManager isExecutableFileAtPath:testFilePath]?@"YES":@"NO");
常见的NSFileManager文件方法
-(NSData *)contentsAtPath:path //从一个文件读取数据
-(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr //向一个文件写入数据(能否写入由其attributes决定)
-(BOOL)removeItemAtPath:path error:err //删除一个文件
-(BOOL)moveItemAtPath:from toPath:to error:err //重命名或者移动一个文件(to不能是已存在的)
-(BOOL)copyItemAtPath:from toPath:to error:err //复制文件(to不能是已存在的) -(BOOL)contentsEqualAtPath:path andPath:path2 //比较两个文件的内容 -(BOOL)fileExistAtPath:path //测试文件是否存在 -(BOOL)isReadableFileAtPath:path //测试文件是否存在,并且是否能执行读操作 -(BOOL)isWriteableFileAtPath:path //测试文件是否存在,并且是否能执行写操作 -(NSDictionary *)attributesOfItemAtPath:path error:err //获取文件的属性 -(BOOL)setAttributesOfItemAtPath:attr error:err //更改文件的属性
NSFileMange 此类主要是对文件进行的操作以及文件信息的获取
NSFileHandle 此类主要是对文件内容进行读取和写入操作
+ (id)fileHandleForReadingAtPath:(NSString *)path 打开一个文件准备读取
+ (id)fileHandleForWritingAtPath:(NSString *)path 打开一个文件准备写入
+ (id)fileHandleForUpdatingAtPath:(NSString *)path 打开一个文件准备更新
- (NSData *)availableData; 从设备或通道返回可用的数据
- (NSData *)readDataToEndOfFile; 从当前的节点读取到文件的末尾
- (NSData *)readDataOfLength:(NSUInteger)length; 从当前节点开始读取指定的长度数据
- (void)writeData:(NSData *)data; 写入数据
- (unsigned long long)offsetInFile; 获取当前文件的偏移量
- (void)seekToFileOffset:(unsigned long long)offset; 跳到指定文件的偏移量
- (unsigned long long)seekToEndOfFile; 跳到文件末尾
- (void)truncateFileAtOffset:(unsigned long long)offset; 将文件的长度设为offset字节
- (void)closeFile; 关闭文件