文件管理器侧重于文件的操作,我们可以实现文件的创建,文件的移动(剪切),文件的复制。
// 1.文件创建
// 拼接文件路径
NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
filePath = [filePath stringByAppendingPathComponent:@"createFile.txt"];
// 判断文件是否存在
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
NSLog(@"%@",filePath);
if (isExists) {
NSLog(@"已经存在");
}else {
NSString *content = @"我有一对象";
// 创建文件
BOOL isCreate = [[NSFileManager defaultManager] createFileAtPath:filePath contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
if (isCreate) {
NSLog(@"创建成功");
}else {
NSLog(@"创建失败");
}
}
// 2、文件的剪切
// 注意点:文件的剪切和赋值需要注意,剪切和复制的最终路径不能存在文件(路径上面只能是空的)跨文件夹的话,文件夹一定得先存在,才能移动复制成功
// 拼接文件路径
// 相当于获取的时候Documents文件夹的路径
NSString *lastPath = [filePath stringByDeletingLastPathComponent];
// 拼接一个新的文件夹路径
NSString *newPath = [lastPath stringByAppendingPathComponent:@"Move"];
// 1、创建文件夹
if ([[NSFileManager defaultManager] fileExistsAtPath:newPath]) {
// 当文件夹存在的时候需要干的事
NSLog(@"文件夹已经存在");
// 拼接文件路径
NSString *movePath = [newPath stringByAppendingPathComponent:@"createFile.txt"];
// // 移动
// BOOL isMoving = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:movePath error:nil];
// if (isMoving) {
//
// NSLog(@"移动成功");
// } else {
//
// NSLog(@"移动失败");
// }
// 复制
BOOL isCopying = [[NSFileManager defaultManager]copyItemAtPath:filePath toPath:movePath error:nil];
if (isCopying) {
NSLog(@"复制成功");
} else {
NSLog(@"复制失败");
}
}else {
// 当文件夹不存时候需要做的事
// 创建文件夹
// YES同上
BOOL isCreating = [[NSFileManager defaultManager]createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:nil];
if (isCreating) {
NSLog(@"创建成功");
// 拼接文件路径
NSString *movePath = [newPath stringByAppendingPathComponent:@"createFile.txt"];
// // 移动
// BOOL isMoving = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:movePath error:nil];
// if (isMoving) {
//
// NSLog(@"移动成功");
// } else {
//
// NSLog(@"移动失败");
// }
// 复制
BOOL isCopying = [[NSFileManager defaultManager]copyItemAtPath:filePath toPath:movePath error:nil];
if (isCopying) {
NSLog(@"复制成功");
} else {
NSLog(@"复制失败");
}
} else {
NSLog(@"创建失败");
}
}
}
