#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);
}