#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self handleNSFileManage];
}
// 文件管理
- (void)handleNSFileManage{
// NSFileManager 是一個單例類,我們稱之為文件管理類,是一個專門用來管理文件的工具,主要可以完成以下功能:文件的添加,文件的刪除,文件的移動,文件的拷貝;
// 創建文件管理對象
NSFileManager *fileManage = [NSFileManager defaultManager];
// 1.文件的添加
// 例如:要在Documents文件夾下創建一個File1文件夾
// ①首先要獲取Documents文件夾路徑
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject];
// ②接着需要准備要創建的文件路徑
NSString *File1Path = [documentsPath stringByAppendingPathComponent:@"Flie1"];
// ③創建文件夾
// 參數1:文件路徑
// 參數2:如果文件中已經有別的目錄,是否還要創建
// 參數3,4:屬性,報錯信息,都給nil
// 用來判斷要創建的文件是否存在
BOOL isHave = [fileManage fileExistsAtPath:File1Path];
if (isHave) {
NSLog(@"文件已存在");
}else{
NSLog(@"文件不存在");
BOOL isSuccess = [fileManage createDirectoryAtPath:File1Path withIntermediateDirectories:YES attributes:nil error:nil];
NSLog(@"%@",isSuccess ? @"創建成功" : @"創建失敗");
}
NSLog(@"%@",File1Path);
// 2.文件的刪除
// 判斷要刪除的文件是否存在
if ([fileManage fileExistsAtPath:File1Path]) {
NSLog(@"文件存在");
// 刪除
BOOL isSuccess = [fileManage removeItemAtPath:File1Path error:nil];
NSLog(@"%@",isSuccess ? @"刪除成功" : @"刪除失敗");
}else{
NSLog(@"文件不存在");
}
// 3.文件的拷貝
// 簡單示范:准備一個Love.txt文件拖入工程,拷貝到File1文件夾中
// ①獲取要拷貝的文件路徑
NSString *lovePath = [[NSBundle mainBundle]pathForResource:@"Love" ofType:txt];
// ②准備要拷貝過去的文件路徑
NSString *toLovePath = [File1Path stringByAppendingPathComponent:@"Love.txt"];
// 簡單判斷拷貝過去的文件路徑是否存在
if (![fileManage fileExistsAtPath:toLovePath]) {
BOOL isSuccess = [fileManage copyItemAtPath:lovePath toPath:toLovePath error:nil];
NSLog(@"%@",isSuccess ? @"拷貝成功" : @"拷貝失敗");
}
// 4.文件的移動
// 例如:將file1文件移動到library文件夾下
// ①獲取library文件路徑
NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)lastObject];
// 獲取在libraryPath文件中加入file1的路徑
NSString *toFilePath = [libraryPath stringByAppendingPathComponent:@"File1"];
if (![fileManage fileExistsAtPath:toFilePath]) {
BOOL isSuccess = [fileManage moveItemAtPath:File1Path toPath:toFilePath error:nil];
NSLog(@"%@",isSuccess ? @"移動成功" : @"移動失敗");
}
// 通過NSFileManage計算文件的大小
// 計算toLovePath路徑下的文件大小
// NSDictionary *info = [fileManage attributesOfItemAtPath:toLovePath error:nil];
// NSLog(@"%lfM",info.fileSize/1024.0/1024.0);
}