iOS文件的剪切
2016-01-06 本文已影响611人
船长_
步骤:
- 1.获取需要剪切文件(夹)的路径from,和要剪切到哪里的路径to
- 2.获取文件管理者对象(单例)
- 3.利用文件管理者对象获取数组
- 4.遍历数组,拼接文件,利用文件管理者剪切文件
方法一:
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSString *from = @"/Users/chuanzhang/Desktop/from";
NSString *to = @"/Users/chuanzhang/Desktop/to";
// 单例对象
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *subPathA = [manager subpathsAtPath:from]; // 文件夹内所有的文件名称
NSLog(@"%@",subPathA);
for (int i = 0; i<subPathA.count; i++) {
// 拼接路径
NSString *fileName = subPathA[i];
NSString *fullPath = [from stringByAppendingPathComponent:fileName]; // 这个方法会自动加斜杠
NSString *toPath = [to stringByAppendingPathComponent:fileName];
NSLog(@"%@",toPath);
[manager moveItemAtPath:fullPath toPath:toPath error:nil];
}
}
方法二:文件剪切属于耗时操作,应该放在子线程中进行
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
NSString *from = @"/Users/chuanzhang/Desktop/from";
NSString *to = @"/Users/chuanzhang/Desktop/to";
NSFileManager *manager = [NSFileManager defaultManager];
NSArray *subPathA = [manager subpathsAtPath:from]; // 文件夹内所有的文件名称
// NSLog(@"%@",subPathA);
NSInteger count = [subPathA count];
// dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// GCD迭代,遍历数组
dispatch_queue_t queue = dispatch_queue_create("com.chuanzhang", DISPATCH_QUEUE_CONCURRENT);
dispatch_apply(count, queue, ^(size_t i) {
// 拼接路径
NSString *fileName = subPathA[i];
NSString *fullPath = [from stringByAppendingPathComponent:fileName]; // 这个方法会自动加斜杠
NSString *toPath = [to stringByAppendingPathComponent:fileName];
// NSLog(@"%@",toPath);
[manager moveItemAtPath:fullPath toPath:toPath error:nil];
NSLog(@"%@--",[NSThread currentThread]);
});
}
文件剪切.png
- 注意:如图,GCD迭代会开启子线程,但是也会在主线程中执行