@fiy-fish
2015-07-13T21:22:47.000000Z
字数 2676
阅读 1377
Objective-c
#import <Foundation/Foundation.h>
#import "MyFileManager.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
MyFileManager *manager = [[MyFileManager alloc] init];
[manager managerFileForPath:@"/Users/qianfeng/Desktop/action"];
}
return 0;
}
#import <Foundation/Foundation.h>
@interface MyFileManager : NSObject
-(void)managerFileForPath:(NSString *)path;
@end
#import "MyFileManager.h"
/*
4.设计一个文件管理器
实现功能:
将dir目录下的所有文件分类管理
dir目录下有各种后缀的文件 以及没有尾缀的文件
检索目录,按照后缀名创建子目录,把该后缀名的文件全丢进去
没有尾缀的创建一个other目录,把没有尾缀的文件全丢进去
不需要支持双尾缀
不用管理文件夹
*/
/*
1.创建一个管理器类
2.遍历目录(浅遍历)
3.干掉文件夹
4.取出后缀,将文件名和后缀做关联
5.创建目录
6.移动文件
*/
@interface MyFileManager ()
@property (nonatomic,strong) NSMutableDictionary *sufAndFileDic;
@end
@implementation MyFileManager
-(void)managerFileForPath:(NSString *)path
{
//创建文件管理器
NSFileManager *manager = [NSFileManager defaultManager];
//浅遍历目录
NSArray *contents = [manager contentsOfDirectoryAtPath:path error:nil];
//删除目录
contents = [self deleteDirectoryInContents:contents withPath:path];
//获取后缀
NSArray *suffixs = [self suffixForFiles:contents];
//利用后缀创建目录
[self createDirectoryBySuffixs:suffixs withPath:path];
//开始移动文件
for(int i = 0; i < suffixs.count; i++)
{
//取后缀
NSString *suf = suffixs[i];
//取后缀对应的所有文件
NSArray *files = [_sufAndFileDic allKeysForObject:suf];
//遍历取出来的所有文件
for(id obj in files)
{
[manager moveItemAtPath:[NSString stringWithFormat:@"%@/%@",path,obj] toPath:[NSString stringWithFormat:@"%@/%@/%@",path,suf,obj] error:nil];
}
}
NSLog(@"%@",suffixs);
}
-(void)createDirectoryBySuffixs:(NSArray *)suffixs withPath:(NSString *)path
{
NSFileManager *manager = [NSFileManager defaultManager];
for(NSString *obj in suffixs)
{
NSString *newPath = [NSString stringWithFormat:@"%@/%@",path,obj];
[manager createDirectoryAtPath:newPath withIntermediateDirectories:NO attributes:nil error:nil];
}
}
//获取后缀,并返回后缀的数组
-(NSArray *)suffixForFiles:(NSArray *)files
{
NSMutableArray *array = [NSMutableArray array];
if(!self.sufAndFileDic)
{
self.sufAndFileDic = [NSMutableDictionary dictionary];
}
for(NSString *obj in files)
{
//检查是否有.
NSRange range = [obj rangeOfString:@"." options:NSBackwardsSearch];
if(range.location != NSNotFound)
{
//有后缀
NSString *suf = [obj substringFromIndex:range.location+1];
if(![array containsObject:suf])
{
[array addObject:suf];
}
[_sufAndFileDic setObject:suf forKey:obj];
}
else
{
//没有后缀
if(![array containsObject:@"other"])
{
[array addObject:@"other"];
}
[_sufAndFileDic setObject:@"other" forKey:obj];
}
}
return array;
}
-(NSArray *)deleteDirectoryInContents:(NSArray *)array withPath:(NSString *)path
{
NSFileManager *manager = [NSFileManager defaultManager];
BOOL isDir = NO;
NSMutableArray *newContents = [NSMutableArray array];
for(int i = 0; i < array.count; i++)
{
NSString *oneFile = array[i];
[manager fileExistsAtPath:[NSString stringWithFormat:@"%@/%@",path,oneFile] isDirectory:&isDir];
if(!isDir)
{
[newContents addObject:oneFile];
}
}
return newContents;
}
@end