文件操作无非就是创建文件、写文件、读文件、复制文件等等这些操作。
常见NSFileManager文件方法
-(NSData *)contentsAtPath:path | 从path所代表的文件中读取数据 |
-(BOOL)createFileAtPath:path contents:(BOOL)data attributes:attr | 将数据写入文件 |
-(BOOL)removeFileAtPath:path handler:handler | 将path所代表的文件删除 |
-(BOOL)movePath:from toPath:to handler:handler | 移动或者重命名文件,to所代表的文件不能是已经存在的文件 |
-(BOOL)copyPath:from toPath:to handler:handler | 复制文件,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 | 改变文件属性
|
常见的NSFileManager目录的方法:
-(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:tohandler:handler | 重命名或移动一个目录,to不能是已经存在的 |
代码实例:
NSString *path ;
NSFileManager *fm;
NSDirectoryEnumerator * dirEnum;
NSArray *dirArray;
fm = [NSFileManager defaultManager];
path = [fm currentDirectoryPath];//get current working directory path
dirEnum = [fm enumeratorAtPath:path];
NSLog(@"Content of %@ :" ,path);
while((path=[dirEnum nextObject])!=nil)
{
NSLog(@"%@",path);
}
dirArray= [fm directoryContentsAtPath:[fm currentDirectoryPath]];
NSLog(@"Content using directoryContentsAtPath :" );
for (path in dirArray) {
NSLog(@"%@",path);
}
//也可以使用NSLog(@"%@",dirArray);来显示整个dirArray的内容,类似PHP中的print_r~
以上用enumeratorAtPath和direcoryContentsAtPath的目录方法对目录下的文件进行枚举,用两个循环分别把得到得不同列表输出来。
使用NSData类
使用文件时,需要频繁地将数据读入一个临时缓存区,它通常称为缓冲区,收集数据后最终输出到文件中,所以也被称之为储存区,类似C#里面的Stream类= =~
值得一起的是NSData类对于32位应用程序,缓冲区最多可存储2GB的数据,对于64位的应用程序,最多可存储8EG的数据。
下面是一个代码实例,先把File读入NSDate,再创建一个文件file2去包存它。
NSFileManager *fm;
NSData *fileData;
fm=[NSFileManager defaultManager];
fileData = [fm contentsAtPath:@"file"];
if(fileData == nil)
{
NSLog(@"File read failed!");
return 1;
}
if([fm createFileAtPath:@"file2" contents:fileData attributes:nil]==NO)
{
NSLog(@"could not create the copy!");
return 2;
}
fm createFileAtPath:@"file2" contents:fileData attributes:nil //创建了一个具有特定属性的文件,然后把NSData对象内容写入这个文件
使用fileAttributesAtPath获取文件属性 及stringWithContentsOfFile获取并输出文件内容,但最终 +[NSString stringWithContentsOfFile:encoding:error:]这里报了个运行时错误.还在寻找解决办法~~~
NSFileManager *fm;
fm = [NSFileManager defaultManager];//写成[fm defaultManager]这样果断就报错了有木有!!!= =!
NSDictionary *attr;
if([fm fileExistsAtPath:@"file"==NO])
{
NSLog(@"could not find file");
return 1;
}
else{
//获取文件大小
// if(([attr=[fm fileAttributesAtPath:@"file"] traverseLink:NO])==nil)
// {
// NSLog(@"could not get size");
// return 2;
// }
// else
// {
// NSLog(@"file2 size is %i bytes",[[attr objectForKey:NSFileSize]intValue]);
// }
NSLog(@"%@",[NSString stringWithContentsOfFile:@"file1" encoding:NSUTF8StringEncoding error:nil]);
}
2.使用路径:NSPathUtilities.h
NSPathUtilities.h包含了NSString的函数和分类的扩展,他允许我们操作路径名。
常用路径工具函数
NSString * NSUserName(void) | 返回当前用户的登录名 |
NSString * NSFullUserName(void) | 返回当前用户的完整用户名 |
NSString * NSHomeDirectory(void) | 返回当前用户主目录的路径 |
NSString * NSHomeDirectoryForUser(NSString *user) | 返回用户user的主目录 |
NSString * NSTemporaryDirectory(void) | 返回可用于创建临时文件的路径目录 |
常用路径工具方法
+(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 | 通过尝试解析~、..、.、和符号链接来标准化路径 |
代码实例:
NSString *tempdir,*path,*homedir ;
NSArray * component;
NSFileManager *fm;
tempdir = NSTemporaryDirectory();//临时文件的目录名
// path = [fm currentDirectoryPath];
//[path lastPathComponent]; //从路径中提取最后一个文件名
//fullpath = [path stringByAppendingPathComponent:fname]; //将文件名附加到路劲的末尾
//extenson = [fullpath pathExtension]; //路径名的文件扩展名
homedir = NSHomeDirectory(); //用户的主目录
component = [homedir pathComponents]; //路径的每个部分
NSLog(@"%@",tempdir);
NSLog(@"%@",homedir);
NSLog(@"%@",component);
结果:当然-这只是面向XP的结果,在MAC下或肾下必然是另一番目录路径了~
NSProcessInfo类:它允许我们设置或检索正在运行得应用程序(进程)的各种类型的信息,这个有关进程的东西听起来就略犀利啊~
NSProcessInfo类 的常用方法
+(NSProcessInfo*)processInfo //返回当前进程的信息
-(NSArray*)arguments //以NSString对象数组的形式返回当前进程的参数
-(NSDictionary *)environment //返回变量/值对词典,以描述当前的环境变量(比如PATH和HOME)及其值
-(int)processIdentifier //返回进程标识符,它是操作系统赋予进程的唯一数字,用于识别每个正在运行的进程
-(NSString*)processName //返回当前正在执行的进程名称
-(NSString *)globallyUniqueString //每次调用这个方法时,都返回不同的单值字符串,可以用这个字符串生成单值临时文件名
-(NSString *)hostname //返回主机系统的名称(在笔者的Mac OS x系统中,返回的是mac-mato-ipad.local)
-(NSUInteger)operatingSystem //返回表示操作系统的数字(在笔者的Mac OS x系统中,返回的是5)
-(NSString *)operatingSystemName //返回操作系统的名称(笔者的Mac OS x系统中返回NSMACHOperatingSystem,可能返回的值定义在NSProgressInfo.h文件中)
-(NSString *)operatingSystemVersionString //返回操作系统的当前版本(笔者的Mac OS x系统中返回Version 10.7.5 (Build 11G56))
-(void)setProcessName:(NSString *)name //将当前进程名称设置为name。应该谨慎地使用这个方法,应为关于进程名称存在一些假设(比如用户默认的设置
代码实例:
NSProcessInfo *proc = [NSProcessInfo processInfo];
NSLog(@"OS:%@ %@",[proc operatingSystemName],[proc operatingSystemVersionString]);
结果:
基本的文件夹操作NSFileHandle:更有效的使用文件
一般而言,我们处理文件时都要经历以下三个步骤
1)打开文件,并获取一个NSFileHandle对象,以便在后面的I/O操作中引用该文件
2)对打开的文件执行I/O操作(读取、写入、更新)
3)关闭文件
常用的NSFileHandle方法:
+(NSFileHandle *)fileHandleForReadingAtPath:path //打开一个文件准备读取
+(NSFileHandle *)fileHandleForWritingAtPath:path //打开一个文件准备写入
+(NSFileHandle *)fileHandleForUpdatingAtPath:path //打开一个文件准备更新(读取或写入)
+(NSData *)availableData //从设备或通道返回可用的数据
+(NSData *)readDataToEndOfFile //读取其余的数据直到文件的末尾(最多UINT_MAX字节)
-(NSData *)readDataOfLength:(NSUInteger)bytes //从文件读取指定字节的内容
-(void)writeData:data //将data写入文件
-(unsigned long long)offsetInFile //获取当前文件的偏移量
-(void)seekToFileOffset:offset //设置当前文件偏移量
-(unsigned long long)seekToEndOfFile //将文件的偏移量定位到文件的末尾,同时返回文件的大小
-(void)truncateFileAtOffset:offset //将文件的长度设置为offset字节(如果需要,可以填充内容)
-(void)closeFile //关闭文件
代码实例:
NSFileHandle *inFile, *outFile;
NSData *buffer;
//[[NSFileManager defaultManager] createFileAtPath:@"test.txt" contents:@"sdfjdsfdf" attributes:nil];
//打开test文件用于读取操作
inFile = [NSFileHandle fileHandleForReadingAtPath:@"file"];
if(inFile == nil)
{
NSLog(@"Open of file for reading failed!");
return 1;
}
//创建一个文件用于写数据(第一次是必要的)
[[NSFileManager defaultManager] createFileAtPath:@"testout.txt" contents:nil attributes:nil] ;
//打开testout.txt文件用于写入操作
outFile = [NSFileHandle fileHandleForWritingAtPath:@"testout.txt"];
if(outFile == nil)
{
NSLog(@"Open of testout.txt for writing failed!");
return 2;
}
//
[outFile truncateFileAtOffset:0];
//从inFile中读取数据,并将其写入到outFile中
buffer = [inFile readDataToEndOfFile];
[outFile writeData:buffer];
//关闭两个文件
[inFile closeFile];
[outFile closeFile];
//验证文件的内容是否写入-输出
NSLog(@"%@",[NSString stringWithContentsOfFile:@"testout.txt" encoding:NSUTF8StringEncoding error:nil]);
代码实例:将一个文件的内容附加到另一个文件里面,注意的是需要打开一个读取的文件及写入的文件,类似输入输出流~
NSFileHandle *inFile , *outFile;
NSData *buffer;
inFile = [NSFileHandle fileHandleForReadingAtPath:@"file"];
outFile = [NSFileHandle fileHandleForWritingAtPath:@"file2"];
[outFile seekToEndOfFile];
buffer = [inFile readDataToEndOfFile];
//return 0;
[outFile writeData:buffer];
[inFile closeFile];
[outFile closeFile];
总结下在文件操作中遇到的一个小问题,就是路径问题,
在MAC下获取路径需要通过路径操作类如NSPathUtilities等去取得正确路径才能正常使用操作文件。
实例代码:
//NSLog(@"1326");
NSFileManager *f;
f=[NSFileManager defaultManager];
NSString *home;
home =[@"~" stringByExpandingTildeInPath];
NSDirectoryEnumerator *direnum;
direnum =[f enumeratorAtPath:home];
NSMutableArray *files;
files =[NSMutableArray arrayWithCapacity:42];
NSString *filename;
while(filename=[direnum nextObject])
{
if([[filename pathExtension]isEqualTo:@"jpg"]){
[files addObject:filename];
}
}
NSEnumerator *fileenum;
fileenum = [files objectEnumerator];
while(filename = [fileenum nextObject])
{
NSLog(@"%@",filename);
}
枚举便利主目录文件夹下的图片~