NSFileManager *fileManager = [NSFileManager defaultManager];
//在这里获取应用程序Documents文件夹里的文件及文件夹列表
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
NSError *error = nil;
NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];
以下这段代码则可以列出给定一个文件夹里的所有子文件夹名
NSMutableArray *dirArray = [[NSMutableArray alloc] init];
BOOL isDir = NO;
//在上面那段程序中获得的fileList中列出文件夹名
for (NSString *file in fileList) {
NSString *path = [documentDir stringByAppendingPathComponent:file];
[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
if (isDir) {
[dirArray addObject:file];
}
isDir = NO;
}
NSLog(@"Every Thing in the dir:%@",fileList);
NSLog(@"All folders:%@",dirArray);
2.filemanager常见操作
措施名称 描述
-(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 改变文件属性