剪切文件的两种方法
2016-10-10 本文已影响14人
IreneWu
1.一般实现
- (void)moveFile {
NSString *from = @"/Users/dianjoy/Desktop/from";
NSString *to = @"/Users/dianjoy/Desktop/to";
NSFileManager *manager = [NSFileManager defaultManager];
//遍历这个目录的第一种方法
NSArray *subpaths = [manager subpathsAtPath:from];
NSLog(@"%@", subpaths);
// //遍历这个目录的第二种方法(深度遍历,会递归枚举它的内容)
// NSDirectoryEnumerator *enumer1 = [manager enumeratorAtPath:from];
// //遍历这个目录的第三种方法(不递归枚举文件夹种的内容)
// NSDirectoryEnumerator *enumer2 = [manager directoryContentsAtPath:from];
// for (NSDirectoryEnumerator *en in enumer1) {
// NSLog(@"%@", en);
// }
NSInteger count = [subpaths count];
for (NSInteger i = 0; i < count; i++) {
NSString *subpath = subpaths[i];
NSString *fullPath = [from stringByAppendingPathComponent:subpath];
NSString *fileName = [to stringByAppendingPathComponent:subpath];
//剪切
[manager moveItemAtPath:fullPath toPath:fileName error:nil];
}
}
2.快速迭代(开多个线程并发完成迭代操作)
- (void)moveFile1 {
NSString *from = @"/Users/dianjoy/Desktop/from";
NSString *to = @"/Users/dianjoy/Desktop/to";
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *subpaths = [manager subpathsAtPath:from];
NSLog(@"%@", subpaths);
NSInteger count = [subpaths count];
//创建队列(并发队列)
dispatch_queue_t queue = dispatch_queue_create("com.downloadqueue", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(count, queue, ^(size_t index) {
NSString *subpath = subpaths[index];
NSString *fullPath = [from stringByAppendingPathComponent:subpath];
NSString *fileName = [to stringByAppendingPathComponent:subpath];
//剪切
[manager moveItemAtPath:fullPath toPath:fileName error:nil];
NSLog(@"%@", [NSThread currentThread]);
});
}