NSFileManager操作

1.创建

NSString *path1 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"];
NSString *path2 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file2/subFile"];
NSString *path3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"symboliclinkPath"];
NSData *data = [@"message" dataUsingEncoding:NSUTF8StringEncoding];

NSURL *url1 = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"url1"]];
NSURL *url2 = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"url2"]];

//初始化
NSFileManager *manager = [NSFileManager defaultManager];
//创建一个文件
BOOL result1 = [manager createFileAtPath:path1 contents:data attributes:nil];
//创建一个目录
BOOL result2 = [manager createDirectoryAtPath:path2 withIntermediateDirectories:YES attributes:nil error:nil];
//创建一个符号链接  指向path3
BOOL result3 = [manager createSymbolicLinkAtPath:path3 withDestinationPath:path1 error:nil];
//通过url创建一个目录
BOOL resultU1 = [manager createDirectoryAtURL:url1 withIntermediateDirectories:YES attributes:nil error:nil];
//通过url创建一个符号链接 指向path3
BOOL resultU2 = [manager createSymbolicLinkAtURL:url2 withDestinationURL:[NSURL fileURLWithPath:path1] error:nil];

if (resultU2) {
    NSLog(@"创建成功");
}else {
    NSLog(@"创建失败");
}

2.获取指定目录中所有的目录与项目

//返回所有一级目录名和项目名
NSArray *array = [manager contentsOfDirectoryAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject error:nil];
//返回所有一级url 这里的option参数是不显示隐藏的文件
NSArray *array2 = [manager contentsOfDirectoryAtURL:[NSURL fileURLWithPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject] includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

//返回一个枚举选择器
NSDirectoryEnumerator *kk = [manager enumeratorAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file2/subFile"]];

//返回所有目录与项目 包含目录下的所有子目录 直至没有子目录为止
NSArray *subs = [manager subpathsAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject];

//返回所有目录与项目 包含目录下的所有子目录 直至没有子目录为止
NSArray *subdiS = [manager subpathsAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject];
NSLog(@"%@,%@,%@,%@,%@",array,array2,kk.directoryAttributes,subs,subdiS);

3.移除与替换

//移除指定url目录或项目
BOOL result = [manager removeItemAtURL:[NSURL fileURLWithPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject] error:nil];
//移除指定path目录或项目
BOOL result = [manager removeItemAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject error:nil];
//替换 options参数保存原数据 改名tttt
BOOL result = [manager replaceItemAtURL:[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"]] withItemAtURL:[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fileTe"]] backupItemName:@"tttt" options:NSFileManagerItemReplacementWithoutDeletingBackupItem resultingItemURL:nil error:nil];
if (result) {
    NSLog(@"移除成功");
}else {
    NSLog(@"移除失败");
}

4.项目的移动与复制

//将指定url移动到新url 并删除原url
BOOL result = [manager moveItemAtURL:[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"]] toURL:[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fileeeee"]] error:nil];
//将指定path移动到新path 并删除原path
BOOL result = [manager moveItemAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"] toPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fileeeee"] error:nil];

//将指定url复制到新url
BOOL result = [manager copyItemAtURL:[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"]] toURL:[NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fileeeee"]] error:nil];
//将指定path复制到新path
BOOL result = [manager copyItemAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"] toPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"fileeeee"] error:nil];


if (result) {
    NSLog(@"移动成功");
}else {
    NSLog(@"移动失败");
}

5.确定文件是否可以访问

//返回一个布尔值,指定路径中的文件或目录是否存在。
- fileExistsAtPath:

//返回一个布尔值,指定路径中的文件或目录是否存在。isDirectory参数表示该路径指向的是一个目录或普通文件。
- fileExistsAtPath:isDirectory:

//返回一个布尔值,该值指示调用对象是否能够读取指定的文件。
- isReadableFileAtPath:

//返回一个布尔值,该值指示调用对象是否能够写入指定的文件。
- isWritableFileAtPath:

//返回一个布尔值,该值指示操作系统是否能够执行指定的文件。
- isExecutableFileAtPath:

//返回一个布尔值,该值指示调用对象是否能够删除指定的文件。
- isDeletableFileAtPath:

6.获取项目中数据

//存储的数据是string类型
NSData *data = [manager contentsAtPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"file1"]];
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);

7.获取文件大小

//获取文件大小
- (NSInteger)fileSize {
    __block NSInteger totalByteSize = 0;
    NSString *directoryPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"searchCache"] stringByAppendingPathComponent:kSearchCahceID];
    
    BOOL isDirectory = NO;
    BOOL isLife = [_manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
    if (!isLife) return totalByteSize;//not directory
    if (isDirectory) {
        NSArray *files = [_manager subpathsAtPath:directoryPath];
        [files enumerateObjectsUsingBlock:^(NSString * _Nonnull fileName, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
            NSDictionary *attr = [_manager attributesOfItemAtPath:filePath error:nil];
            totalByteSize += [attr[NSFileSize] integerValue];
        }];
    }
    
    return totalByteSize;
}


//递归获取所有文件  慎用 除非确定是简单递归 不然可能死循环
- (NSArray *)filesWithDirectoryPath:(NSString *)directoryPath files:(NSMutableArray *)files{
    BOOL isDirectory = NO;
    BOOL isLife = [_manager fileExistsAtPath:directoryPath isDirectory:&isDirectory];
    if (!isLife) return files;//directory die
    
    if (isDirectory) {
        NSArray *fileNames = [_manager subpathsAtPath:directoryPath];\
        for (NSString *fileName in fileNames) {
            NSString *filePath = [directoryPath stringByAppendingPathComponent:fileName];
            if ([fileName rangeOfString:@"/"].location != NSNotFound) continue;//continue directory/directory/file  or directory/file
            
            BOOL isDirectory = NO;
            [_manager fileExistsAtPath:filePath isDirectory:&isDirectory];
            if (isDirectory) {
                [self filesWithDirectoryPath:filePath files:files];
            }else {
                @synchronized(self) {
                    [files addObject:filePath];
                }
            }
        }
    }else {
        @synchronized(self) {
            [files addObject:directoryPath];
        }
    }
    return files;
}

你可能感兴趣的:(NSFileManager操作)