您的位置:首页 > 移动开发 > IOS开发

iOS文件操作NSFileManager和NSFileHandle

2015-08-19 11:42 531 查看
NSFileManager是一个单列类,也是一个文件管理器。可以通过NSFileManager创建文件夹、创建文件、写文件、读文件内容等等基本功能。
下面将介绍NSFileManager文件操作的十个小功能。我们在Documents里面进行举例,首先是获取Documents的路径。这个在iOS开发之沙盒机制(SandBox)已经详细讲解过了。获取Documents路径方法如下:

-(NSString*)getDocumentsPath
{
//获取Documents路径
NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString*path=[pathsobjectAtIndex:0];
NSLog(@"path:%@",path);
returnpath;
}

- (void)read
{
//读取数据
NSFileHandle *file = [NSFileHandle fileHandleForReadingAtPath: @"test.xml"];
NSData *data = [file readDataToEndOfFile];//得到xml文件 //读取到NSDate中

NSString* aStr;
aStr = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding]; //转换为NSString
NSLog( @"aStr is %@", aStr );

[file closeFile];

}

创建文件夹

-(void)createDirectory{
NSString*documentsPath=[selfgetDocumentsPath];
NSFileManager*fileManager=[NSFileManagerdefaultManager];
NSString*iOSDirectory=[documentsPathstringByAppendingPathComponent:@"iOS"];
BOOLisSuccess=[fileManagercreateDirectoryAtPath:iOSDirectorywithIntermediateDirectories:YESattributes:nilerror:nil];
if(isSuccess){
NSLog(@"success");
}else{
NSLog(@"fail");
}
}

创建文件

-(void)createFile{
NSString*documentsPath=[selfgetDocumentsPath];
NSFileManager*fileManager=[NSFileManagerdefaultManager];
NSString*iOSPath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
BOOLisSuccess=[fileManagercreateFileAtPath:iOSPathcontents:nilattributes:nil];
if(isSuccess){
NSLog(@"success");
}else{
NSLog(@"fail");
}
}

写文件

-(void)writeFile{
NSString*documentsPath=[selfgetDocumentsPath];
NSString*iOSPath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
NSString*content=@"我要写数据啦";
BOOLisSuccess=[contentwriteToFile:iOSPathatomically:YESencoding:NSUTF8StringEncodingerror:nil];
if(isSuccess){
NSLog(@"writesuccess");
}else{
NSLog(@"writefail");
}
}

读取文件内容

-(void)readFileContent{
NSString*documentsPath=[selfgetDocumentsPath];
NSString*iOSPath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
NSString*content=[NSStringstringWithContentsOfFile:iOSPathencoding:NSUTF8StringEncodingerror:nil];
NSLog(@"readsuccess:%@",content);
}

判断文件是否存在

-(BOOL)isSxistAtPath:(NSString*)filePath{
NSFileManager*fileManager=[NSFileManagerdefaultManager];
BOOLisExist=[fileManagerfileExistsAtPath:filePath];
returnisExist;
}

计算文件大小

-(unsignedlonglong)fileSizeAtPath:(NSString*)filePath{
NSFileManager*fileManager=[NSFileManagerdefaultManager];
BOOLisExist=[fileManagerfileExistsAtPath:filePath];
if(isExist){
unsignedlonglongfileSize=[[fileManagerattributesOfItemAtPath:filePatherror:nil]fileSize];
returnfileSize;
}else{
NSLog(@"fileisnotexist");
return0;
}
}

计算整个文件夹中所有文件大小

-(unsignedlonglong)folderSizeAtPath:(NSString*)folderPath{
NSFileManager*fileManager=[NSFileManagerdefaultManager];
BOOLisExist=[fileManagerfileExistsAtPath:folderPath];
if(isExist){
NSEnumerator*childFileEnumerator=[[fileManagersubpathsAtPath:folderPath]objectEnumerator];
unsignedlonglongfolderSize=0;
NSString*fileName=@"";
while((fileName=[childFileEnumeratornextObject])!=nil){
NSString*fileAbsolutePath=[folderPathstringByAppendingPathComponent:fileName];
folderSize+=[selffileSizeAtPath:fileAbsolutePath];
}
returnfolderSize/(1024.0*1024.0);
}else{
NSLog(@"fileisnotexist");
return0;
}
}

删除文件

-(void)deleteFile{
NSString*documentsPath=[selfgetDocumentsPath];
NSFileManager*fileManager=[NSFileManagerdefaultManager];
NSString*iOSPath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
BOOLisSuccess=[fileManagerremoveItemAtPath:iOSPatherror:nil];
if(isSuccess){
NSLog(@"deletesuccess");
}else{
NSLog(@"deletefail");
}
}

移动文件

-(void)moveFileName
{
NSString*documentsPath=[selfgetDocumentsPath];
NSFileManager*fileManager=[NSFileManagerdefaultManager];
NSString*filePath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
NSString*moveToPath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
BOOLisSuccess=[fileManagermoveItemAtPath:filePathtoPath:moveToPatherror:nil];
if(isSuccess){
NSLog(@"renamesuccess");
}else{
NSLog(@"renamefail");
}
}

重命名

-(void)renameFileName
{
//通过移动该文件对文件重命名
NSString*documentsPath=[selfgetDocumentsPath];
NSFileManager*fileManager=[NSFileManagerdefaultManager];
NSString*filePath=[documentsPathstringByAppendingPathComponent:@"iOS.txt"];
NSString*moveToPath=[documentsPathstringByAppendingPathComponent:@"rename.txt"];
BOOLisSuccess=[fileManagermoveItemAtPath:filePathtoPath:moveToPatherror:nil];
if(isSuccess){
NSLog(@"renamesuccess");
}else{
NSLog(@"renamefail");
}
}

常用路径工具函数

NSString * NSUserName(); 返回当前用户的登录名

NSString * NSFullUserName(); 返回当前用户的完整用户名

NSString * NSHomeDirectory(); 返回当前用户主目录的路径

NSString * NSHomeDirectoryForUser(); 返回用户user的主目录

NSString * NSTemporaryDirectory(); 返回可用于创建临时文件的路径目录

常用路径工具方法

-(NSString *) pathWithComponents:components 根据components(NSArray对象)中元素构造有效路径

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

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

-(NSString *)pathExtension 路径扩展名

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

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

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

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

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

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

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

-

使用路径NSPathUtilities.h

tempdir = NSTemporaryDirectory(); 临时文件的目录名

path = [fm currentDirectoryPath];

[path lastPathComponent]; 从路径中提取最后一个文件名

fullpath = [path stringByAppendingPathComponent:fname];将文件名附加到路劲的末尾

extenson = [fullpath pathExtension]; 路径名的文件扩展名

homedir = NSHomeDirectory();用户的主目录

component = [homedir pathComponents]; 路径的每个部分

NSProcessInfo类:允许你设置或检索正在运行的应用程序的各种类型信息

(NSProcessInfo *)processInfo 返回当前进程的信息

-(NSArray*)arguments 以NSString对象数字的形式返回当前进程的参数

-(NSDictionary *)environment 返回变量/值对词典。描述当前的环境变量

-(int)processIdentity 返回进程标识

-(NSString *)processName 返回进程名称

-(NSString *)globallyUniqueString 每次调用该方法都会返回不同的单值字符串,可以用这个字符串生成单值临时文件名

-(NSString *)hostname 返回主机系统的名称

-(unsigned int)operatingSystem 返回表示操作系统的数字

-(NSString *)operatingSystemName 返回操作系统名称

-(NSString *)operatingSystemVersionString 返回操作系统当前版本

-(void)setProcessName:(NSString *)name 将当前进程名称设置为name

============================================================================

NSFileHandle类允许更有效地使用文件。

可以实现如下功能:

1、打开一个文件,执行读、写或更新(读写)操作;

2、在文件中查找指定位置;

3、从文件中读取特定数目的字节,或将特定数目的字节写入文件中

另外,NSFileHandle类提供的方法也可以用于各种设备或套接字。一般而言,我们处理文件时都要经历以下三个步骤:

1、打开文件,获取一个NSFileHandle对象(以便在后面的I/O操作中引用该文件)。

2、对打开文件执行I/O操作。

3、关闭文件。

NSFileHandle *fileHandle = [[NSFileHandle alloc]init];

fileHandle = [NSFileHandle fileHandleForReadingAtPath:path]; //打开一个文件准备读取

fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];

fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];

fileData = [fileHandle availableData]; // 从设备或者通道返回可用的数据

fileData = [fileHandle readDataToEndOfFile];

[fileHandle writeData:fileData]; //将NSData数据写入文件

[fileHandle closeFile]; //关闭文件 ... ...

注:NSFileHandle类没有提供创建文件的功能,所以必须使用NSFileManager来创建文件

常用路径工具函数

NSString * NSUserName(); 返回当前用户的登录名

NSString * NSFullUserName(); 返回当前用户的完整用户名

NSString * NSHomeDirectory(); 返回当前用户主目录的路径

NSString * NSHomeDirectoryForUser(); 返回用户user的主目录

NSString * NSTemporaryDirectory(); 返回可用于创建临时文件的路径目录

常用路径工具方法

-(NSString *) pathWithComponents:components 根据components(NSArray对象)中元素构造有效路径

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

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

-(NSString *)pathExtension 路径扩展名

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

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

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

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

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

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

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

-

使用路径NSPathUtilities.h

tempdir = NSTemporaryDirectory(); 临时文件的目录名

path = [fm currentDirectoryPath];

[path lastPathComponent]; 从路径中提取最后一个文件名

fullpath = [path stringByAppendingPathComponent:fname];将文件名附加到路劲的末尾

extenson = [fullpath pathExtension]; 路径名的文件扩展名

homedir = NSHomeDirectory();用户的主目录

component = [homedir pathComponents]; 路径的每个部分

NSProcessInfo类:允许你设置或检索正在运行的应用程序的各种类型信息

(NSProcessInfo *)processInfo 返回当前进程的信息

-(NSArray*)arguments 以NSString对象数字的形式返回当前进程的参数

-(NSDictionary *)environment 返回变量/值对词典。描述当前的环境变量

-(int)processIdentity 返回进程标识

-(NSString *)processName 返回进程名称

-(NSString *)globallyUniqueString 每次调用该方法都会返回不同的单值字符串,可以用这个字符串生成单值临时文件名

-(NSString *)hostname 返回主机系统的名称

-(unsigned int)operatingSystem 返回表示操作系统的数字

-(NSString *)operatingSystemName 返回操作系统名称

-(NSString *)operatingSystemVersionString 返回操作系统当前版本

-(void)setProcessName:(NSString *)name 将当前进程名称设置为name

============================================================================

NSFileHandle类允许更有效地使用文件。

可以实现如下功能:

1、打开一个文件,执行读、写或更新(读写)操作;

2、在文件中查找指定位置;

3、从文件中读取特定数目的字节,或将特定数目的字节写入文件中

另外,NSFileHandle类提供的方法也可以用于各种设备或套接字。一般而言,我们处理文件时都要经历以下三个步骤:

1、打开文件,获取一个NSFileHandle对象(以便在后面的I/O操作中引用该文件)。

2、对打开文件执行I/O操作。

3、关闭文件。

NSFileHandle *fileHandle = [[NSFileHandle alloc]init];

fileHandle = [NSFileHandle fileHandleForReadingAtPath:path]; //打开一个文件准备读取

fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];

fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];

fileData = [fileHandle availableData]; // 从设备或者通道返回可用的数据

fileData = [fileHandle readDataToEndOfFile];

[fileHandle writeData:fileData]; //将NSData数据写入文件

[fileHandle closeFile]; //关闭文件 ... ...

注:NSFileHandle类没有提供创建文件的功能,所以必须使用NSFileManager来创建文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: