NSFileManager&&NSFileHandle

Posted Jk_Chan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了NSFileManager&&NSFileHandle相关的知识,希望对你有一定的参考价值。

NSFileManager:
沙盒根目录有3个文件夹:
1.Documents
建议程序创建产生的文件以及应用浏览产生的文件数据保存在该目录下
iTunes备份与恢复时会包括此目录
2.Library
存储程序的默认设置或其它状态信息
1.Caches
存放缓存文件,保存持久化数据
不被iTunes同步
一般存放一些比较大的文件而又不需要备份的文件
2.Preferences
3.tmp
存放临时文件,不持久化
获取沙盒跟路径:
NSString *homePath=NSHomeDirectory();

获取Documents目录路径:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];

获取Cache目录路径:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];

获取Tmp目录路径:
NSString *tmpPath=NSTemporaryDirectory();

创建文件夹:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
BOOL result=[fileManager createDirectoryAtPath:myDirPath withIntermediateDirectories:YES attributes:nil error:nil];
if(result){
NSLog(@"文件夹创建成功");
}else{
NSLog(@"文件夹创建失败");
}

创建文件:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
BOOL result=[fileManager createFileAtPath:myFilePath contents:nil attributes:nil];
if(result){
NSLog(@"文件创建成功");
}else{
NSLog(@"文件创建失败");
}

写数据到文件:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
//字符串写入
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSString *[email protected]"测试写入内容";
BOOL result=[content writeToFile:myFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
/*数组写入(若元素为自定义类型对象则需实现归档协议,否则写入失败)
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSArray *[email protected][@"a",@"b",@"c"];
BOOL result=[content writeToFile:myFilePath atomically:YES];
*/
/*字典写入(若元素为自定义类型对象则需实现归档协议,否则写入失败)
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.plist"];
NSDictionary *[email protected]{@"key1":@"value1",@"key2",@"value2"};
BOOL result=[content writeToFile:myFilePath atomically:YES];
*/
/*混合数据写入
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSString *temp = @"nihao 世界";
int dataInt = 1234;
float dataFloat = 3.14f;
NSMutableData *writer = [[NSMutableData alloc] init];
[writer appendData:[temp dataUsingEncoding:NSUTF8StringEncoding]];
[writer appendBytes:&dataInt length:sizeof(dataInt)];
[writer appendBytes:&dataFloat length:sizeof(dataFloat)];
[writer writeToFile:myFilePath atomically:YES];
*/
if(result){
NSLog(@"数据写入成功");
}else{
NSLog(@"数据写入失败");
}

读文件数据:
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
//读字符串内容
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSString *content=[NSString stringWithContentsOfFile:myFilePath encoding:NSUTF8StringEncoding error:nil];
/*读数组内容
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
NSArray *content=[NSArray arrayWithContentsOfFile:myFilePath];
*/
/*读字典内容
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.plist"];
NSDictionary *content=[[NSDictionary alloc]initWithContentsOfFile:myFilePath];
*/
/*读混合数据
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
int intData;
float floatData = 0.0;
NSString *stringData;
NSData *reader = [NSData dataWithContentsOfFile:myFilePath];
stringData = [[NSString alloc] initWithData:[reader subdataWithRange:NSMakeRange(0, [temp length])] encoding:NSUTF8StringEncoding];
[reader getBytes:&intData range:NSMakeRange([temp length], sizeof(intData))];
[reader getBytes:&floatData range:NSMakeRange([temp length] + sizeof(intData), sizeof(floatData))];
*/

删除文件:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
BOOL result=[fileManager removeItemAtPath:myFilePath error:nil];
if(result){
NSLog(@"文件删除成功");
}else{
NSLog(@"文件删除失败");
}

修改文件:
把新数据写入到旧数据相应路径上覆盖即可

判断文件是否存在:
NSFileManager *fileManager=[NSFileManager defaultManager];
NSString *docPath=[NSSearchPathForDirectoriesInDomains((NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *myDirPath=[docPath stringByAppendingPathComponent:@"myDir"];
NSString *myFilePath=[myDirPath stringByAppendingPathComponent:@"myFile.txt"];
BOOL isHad=[fileManager isExecutableFileAtPath:myFilePath];
if(isHad){
NSLog(@"文件存在");
}else{
NSLog(@"文件不存在");
}


NSFileManager常用方法:
-(BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
将path所代表的文件删除

-(BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error
移动或者重命名文件,to所代表的文件不能是已经存在的文件

-(BOOL)contentsEqualAtPath:path1 andPath:path2
比较path1和path2所代表的文件

-(BOOL)fileExistsAtPath:path
检查path所代表的文件是否存在

-(BOOL)isReadableFileAtPath:path
检查path所代表的文件是否存在、是否可读

-(BOOL)isWritableFileAtPath:path
检查path所代表的文件是否存在、是否可写

-(NSDictionary *)fileAttributesAtPath:path traverseLink:(BOOL)flag
获取path所代表的文件属性

-(BOOL)changeFileAttributes:attr atPath:path
改变文件属性

-(NSString *)currentDirectoryPath
获取当前目录

-(BOOL)changeCurrentDirectoryPath:path
更改当前目录

-(BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error
复制目录结构,to不能已经存在

-(BOOL)createDirectoryAtPath:path attributes:attr
创建目录

-(BOOL)fileExistsAtPath:(NSString *)path;
路径文件是否存在

-(BOOL)fileExistsAtPath:path isDirectory:(BOOL *)flag
测试文件是否为目录 (flag存储结构yes/no)

-(NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error
列出目录的内容

-(NSDirectoryEnumerator *)enumeratorAtPath:path
枚举目录的内容

-(BOOL)removeFileAtPath:path handler:handler
删除空目录


常用路径(NSString对象)工具方法
-(NSString *) pathWithComponents:components
根据components中元素构造有效路径

-(NSArray *)pathComponents
析构路径,获取路径的各个部分

-(NSString *)lastPathComponent
提取路径的最后一个组成部分

-(NSString *)pathExtension
路径扩展名

-(NSString *)stringByAppendingPathComponent:path
将path添加到现有路径末尾

-(NSString *)stringByAppendingPathExtension:ext
将拓展名添加的路径最后一个组成部分

-(NSString *)stringByDeletingPathComponent
删除路径的最后一个部分

-(NSString *)stringByDeletingPathExtension
删除路径的最后一个部分 的扩展名

-(NSString *)stringByExpandingTildeInPath
将路径中的代字符扩展成用户主目录(~)或指定用户主目录(~user)

-(NSString *)stringByResolvingSymlinksInPath
尝试解析路径中的符号链接

-(NSString *)stringByStandardizingPath
通过尝试解析~、..、.、和符号链接来标准化路径

 

 

 

 

 

 

 


NSFileHandle方法
+(NSFileHandle *)fileHandleForReadingAtPath:path
打开一个文件准备读取

+(NSFileHandle *)fileHandleForWritingAtPath:path
打开一个文件准备写入

+(NSFileHandle *)fileHandleForUpdatingAtPath:path
打开一个文件准备更新(读取和写入)

-(NSData *)availableData
从设备或通道返回可用数据

-(NSData *)readDataToEndOfFile
读取其余的数据直到文件末尾(最多UINT_MAX字节)

-(NSData *)readDataOfLength:(unsigned int)bytes
从文件读取指定数目bytes的内容

-(void)writeData:data
将data写入文件

-(unsigned long long) offsetInFile
获取当前文件的偏移量

-(void)seekToFileOffset:offset
设置当前文件的偏移量

-(unsigned long long) seekToEndOfFile
将当前文件的偏移量定位的文件末尾

-(void)truncateFileAtOffset:offset
将文件的长度设置为offset字节

-(void)closeFile
关闭文件

使用示范:
//要定位到文件 (文件的句柄为databaseHandle)的第10个字节
[databaseHandle seekToFileOffset:10];

//得到相对文件位置,通过获得当前的文件偏移量,然后加上或者减去这个值
[databaseHandle seekToFileOffset:[databaseHandle offsetInFile] + 128];

//在文件中向回移动5个整数所占的子结束
[databaseHandle seekToFileOffset:[databaseHandle offsetInFile] -5 * sizeof(int)];


//向文件追加数据
NSString *homePath = NSHomeDirectory( );
NSString *sourcePath = [homePath stringByAppendingPathConmpone:@"testfile.text"];
NSFileHandle *fielHandle = [NSFileHandle fileHandleForUpdatingAtPath:sourcePath];
[fileHandle seekToEndOfFile]; 将节点跳到文件的末尾
NSString *str = @"追加的数据"
NSData* stringData = [str dataUsingEncoding:NSUTF8StringEncoding];
[fileHandle writeData:stringData]; 追加写入数据
[fileHandle closeFile];

//定位数据
NSFileManager *fm = [NSFileManager defaultManager];
NSString *content = @"abcdef";
[fm createFileAtPath:path contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:path];
NSUInteger length = [fileHandle availabelData] length]; 获取数据长度
[fileHandle seekToFileOffset;length/2]; 偏移量文件的一半
NSData *data = [fileHandle readDataToEndOfFile];
[fileHandle closeFile];

//复制文件
NSFileHandle *infile, *outfile; 输入文件、输出文件
NSData *buffer; 读取的缓冲数据
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *homePath = NSHomeDirectory( );
NSString *sourcePath = [homePath stringByAppendingPathComponent:@"testfile.txt"]; 源文件路径
NSString *outPath = [homePath stringByAppendingPathComponent:@"outfile.txt"]; 输出文件路径
BOOL sucess = [fileManager createFileAtPath:outPath contents:nil attributes:nil];
if (!success){
return N0;
}
infile = [NSFileHandle fileHandleForReadingAtPath:sourcePath]; 创建读取源路径文件
if (infile == nil){
return NO;
}
outfile = [NSFileHandle fileHandleForReadingAtPath:outPath]; 创建病打开要输出的文件
if (outfile == nil){
return NO;
}
[outfile truncateFileAtOffset:0]; 将输出文件的长度设为0
buffer = [infile readDataToEndOfFile]; 读取数据
[outfile writeData:buffer]; 写入输入
[infile closeFile]; 关闭写入、输入文件
[outfile closeFile];


 

以上是关于NSFileManager&&NSFileHandle的主要内容,如果未能解决你的问题,请参考以下文章

Foundation框架 之 NSFileManager 与 copy & mutableCopy

NSFileManager copyItemAtPath toPath

文件夹中的 NSFileManager

ubuntu安装openmpi && ns-3 mpi

NSFileManager

NSFileManager 导致 SourceKit 服务终止