#import "ViewController.h"工具
@implementation ViewControllerspa
- (void)viewDidLoad {對象
[super viewDidLoad];rem
[self handleNSFileManage];string
}it
// 文件管理io
- (void)handleNSFileManage{ast
// NSFileManager 是一個單例類,咱們稱之爲文件管理類,是一個專門用來管理文件的工具,主要能夠完成如下功能:文件的添加,文件的刪除,文件的移動,文件的拷貝;import
// 建立文件管理對象file
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);
}