文件管理器側(cè)重于文件的操作,我們可以實(shí)現(xiàn)文件的創(chuàng)建,文件的移動(dòng)(剪切),文件的復(fù)制。
// 1.文件創(chuàng)建
// 拼接文件路徑
NSString *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
filePath = [filePath stringByAppendingPathComponent:@"createFile.txt"];
// 判斷文件是否存在
BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
NSLog(@"%@",filePath);
if (isExists) {
NSLog(@"已經(jīng)存在");
}else {
NSString *content = @"我有一對(duì)象";
// 創(chuàng)建文件
BOOL isCreate = [[NSFileManager defaultManager] createFileAtPath:filePath contents:[content dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
if (isCreate) {
NSLog(@"創(chuàng)建成功");
}else {
NSLog(@"創(chuàng)建失敗");
}
}
// 2、文件的剪切
// 注意點(diǎn):文件的剪切和賦值需要注意,剪切和復(fù)制的最終路徑不能存在文件(路徑上面只能是空的)跨文件夾的話,文件夾一定得先存在,才能移動(dòng)復(fù)制成功
// 拼接文件路徑
// 相當(dāng)于獲取的時(shí)候Documents文件夾的路徑
NSString *lastPath = [filePath stringByDeletingLastPathComponent];
// 拼接一個(gè)新的文件夾路徑
NSString *newPath = [lastPath stringByAppendingPathComponent:@"Move"];
// 1、創(chuàng)建文件夾
if ([[NSFileManager defaultManager] fileExistsAtPath:newPath]) {
// 當(dāng)文件夾存在的時(shí)候需要干的事
NSLog(@"文件夾已經(jīng)存在");
// 拼接文件路徑
NSString *movePath = [newPath stringByAppendingPathComponent:@"createFile.txt"];
// // 移動(dòng)
// BOOL isMoving = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:movePath error:nil];
// if (isMoving) {
//
// NSLog(@"移動(dòng)成功");
// } else {
//
// NSLog(@"移動(dòng)失敗");
// }
// 復(fù)制
BOOL isCopying = [[NSFileManager defaultManager]copyItemAtPath:filePath toPath:movePath error:nil];
if (isCopying) {
NSLog(@"復(fù)制成功");
} else {
NSLog(@"復(fù)制失敗");
}
}else {
// 當(dāng)文件夾不存時(shí)候需要做的事
// 創(chuàng)建文件夾
// YES同上
BOOL isCreating = [[NSFileManager defaultManager]createDirectoryAtPath:newPath withIntermediateDirectories:YES attributes:nil error:nil];
if (isCreating) {
NSLog(@"創(chuàng)建成功");
// 拼接文件路徑
NSString *movePath = [newPath stringByAppendingPathComponent:@"createFile.txt"];
// // 移動(dòng)
// BOOL isMoving = [[NSFileManager defaultManager] moveItemAtPath:filePath toPath:movePath error:nil];
// if (isMoving) {
//
// NSLog(@"移動(dòng)成功");
// } else {
//
// NSLog(@"移動(dòng)失敗");
// }
// 復(fù)制
BOOL isCopying = [[NSFileManager defaultManager]copyItemAtPath:filePath toPath:movePath error:nil];
if (isCopying) {
NSLog(@"復(fù)制成功");
} else {
NSLog(@"復(fù)制失敗");
}
} else {
NSLog(@"創(chuàng)建失敗");
}
}
}

