您的位置:首页 > 职场人生

黑马程序员——Foundation框架入门:OC中的文件管理

2015-09-09 16:26 441 查看
NSFileManager:用于进行常见的文件、文件夹操作,如拷贝、剪切、创建等。NSFileManager使用的是单例模式。

NSFileManager基本使用

判断文件是否存在

存储文件路径:

NSString *filePath = @”/User/Michael/Desktop/arr.plist”;

调用defaultManager创建一个文件管理的单例对象:

NSFileManager *fm = [NSFileManager defaultManager];

判断是否存在这个文件:

BOOL isYES = [fmfileExistsAtPath:filePath];

判断是否是一个目录

BOOL isPath;
[fm fileExistsAtPath:filePath isDirectory:&isPath];
if(isPath){
NSLog(@"是目录");
}else{
NSLog(@"不是目录")
}


判断文件是否可读

[fm isReadableFileAtPath:filePath];

判断文件是否可写

[fm isWritableFileAtPath:filePath];

判断文件是否可删除

[fm isDeletatbleFileAtPath:filePath];

NSFileManager文件访问

创建文件对象:NSFileManager *fm = [NSFileManager defaultManager];

保存路径:NSString *filePath =@”/User/Michael/Desktop/arr.plist”;

获取文件信息(属性)

获取属性:NSDictionary *dict = [fm attributesOfItemAtPath:filePatherror:nil];

获取指定目录下的文件及子目录

NSArray *subPaths = [fmsubpathsAtPath:filePath];//递归方式,效率较低。

subPaths = [fmsubpathsOfDirectoryAtPath:filePath error: nil];//非递归方式,效率较高,通常使用这个方法。

获取指定目录下的子目录(只获取子目录,不获取其他后代目录)

subPaths = [fm contentsOfDirectoryAtPath:filePath error:nil];

如何创建目录

NSString *createDirPath = @"/User/Michael/Desktop/test";
BOOL isYES = [fm createDirectoryAtPath:createDirPath withIntermediateDirectories:NO attributes:nil error:nil];


关于”withIntermediateDirectories:YES\NO”,当为YES时,创建所给目录的所有父目录,例如如果不存在Desktop文件夹,那么也会创建该文件夹。如果选择NO,则只有父目录都存在才会创建末端目录。

如何创建文件

NSString *str = @"新建文件测试";
NSString *createDirPath =@"/User/Michael/Desktop/test/file.txt";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
BOOL isYES = [fm createFileAtPath:createDirPath content:dataattributes:nil];


如何copy文件

NSString *targetPath =@”/User/Michael/Desktop/test/test1/file.txt”;

[fm copyItemAtPath:createDirPath toPath:targetPath error:nil];

如何移动文件

[fm moveItemAtPath:createDirPath toPath:targetPath error:nil];

如何删除文件

[fm removeItemAtPath:targetPath error:nil];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  foundation 框架