iOS系统Foundatation

iOS NSFileManager 文件管理常用方法介绍

2022-04-30  本文已影响0人  Edviin_2de8

简介

特点
建议使用场景

管理沙盒中的文件或文件夹.

常用方法
image.png
//
//  UIViewController+FileManager.m
//  myview
//
//  Created by mingzhou wang on 2022/4/30.
//

#import "UIViewController+FileManager.h"
@implementation UIViewController (FileManager)

#pragma mark -- 创建文件的路径
-(NSString*)createFilePath:(NSString*)fileName{
    NSString * filePathString = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    return [NSString stringWithFormat:@"%@/%@",filePathString,fileName];
}
#pragma mark 创建文件
-(void)createFile:(NSString*)fileString{
    /**
     创建文件
     @parm createFileAtPath 文件的路径
     @parm contents 文件创建时写入的内容,可为nil
     @parm attributes 文件的属性,可为nil
     */
    BOOL isFile = [[NSFileManager defaultManager] createFileAtPath:[self createFilePath:fileString] contents:nil attributes:nil];
    if (!isFile) {
        NSLog(@"创建失败");
        return;
    }
    /**
     判断文件是否存在
     */
    [self judgeObjectExistence:[self createFilePath:@"NetWork小贱.plist"]];
}
 
 
#pragma mark -- 创建文件夹
-(void)createFolder:(NSString*)folderString{
    /**
     创建文件夹
     
     @parm path 创建文件夹的路径
     @parm createIntermediates 是否展开文件夹的中间目录
     @parm attributes 是创建文件夹设置的属性,可为nil
     @parm error 创建文件夹返回的错误对象,可为nil
     */
    NSError * error = nil;
    BOOL isFolder = [[NSFileManager defaultManager] createDirectoryAtPath:[self createFilePath:folderString] withIntermediateDirectories:YES attributes:nil error:&error];
    if (!isFolder) {
        NSLog(@"createFolder_error:%@",error);
        return;
    }
    /**
     判断文件夹是否存在
     */
    [self judgeObjectExistence:[self createFilePath:@"NetWork"]];
}
 
 
#pragma mark -- 判断文件是否存在
-(void)judgeObjectExistence:(NSString*)objectPath{
    /**
     判断文或者文件夹
     BOOL Existence = [fileManager fileExistsAtPath:objectPath isDirectory:YES];
     */
    BOOL isExistence = [[NSFileManager defaultManager] fileExistsAtPath:objectPath];
    if (!isExistence) {
        NSLog(@"不存在");
        return;
    }
    /**
     判断文件或者文件夹是否可读
     */
    [self judgeObjectReadJurisdiction:objectPath];
    /**
     判断文件或者文件夹是否可写权限
     */
    [self judgeObjectWritJurisdiction:objectPath];
    /**
     判断文件是否是可执行文件
     */
    [self judgeObjectExecutJurisdiction:objectPath];
    /**
     判断是否是可删除的对象
     */
    [self judgeObjectDeletJurisdiction:objectPath];
    /**
     获取可视化的文件字符串
     */
    [self getVisualizationFileString:objectPath];
}
 
 
#pragma mark -- 判断对象的权限是否可读
-(void)judgeObjectReadJurisdiction:(NSString*)objectPath{
    /**
     判断对象是否有可读权限
     @parm path 对象路径
     */
    BOOL isRead = [[NSFileManager defaultManager] isReadableFileAtPath:objectPath];
    if (!isRead) {
        NSLog(@"没有可读权限");
    }
}
 
 
#pragma mark -- 判断对象是否有可写的权限
-(void)judgeObjectWritJurisdiction:(NSString*)objectPath{
    /**
     判断对象是否有可写权限
     @parm path 对象路径
     */
    BOOL isWrit = [[NSFileManager defaultManager] isWritableFileAtPath:objectPath];
    if (!isWrit) {
        NSLog(@"没有可写权限");
    }
}
 
 
#pragma mark -- 判断是否是可执行文件
-(void)judgeObjectExecutJurisdiction:(NSString*)objectPath{
    /**
     判断是否是可执行文件
     @parm path 对象路径
     知识:
     可执行文件 (executable file) 指的是可以由操作系统进行加载执行的文件。
     */
    BOOL isExecut = [[NSFileManager defaultManager] isExecutableFileAtPath:objectPath];
    if (!isExecut) {
        NSLog(@"不是可执行文件");
    }
}
 
 
#pragma mark -- 判断文件或者文件夹是否可以删除
-(void)judgeObjectDeletJurisdiction:(NSString*)objectPath{
    /**
     判断是否是可可删除的对象
     @parm path 对象路径
     */
    BOOL isDelet = [[NSFileManager defaultManager] isDeletableFileAtPath:objectPath];
    if (!isDelet) {
        NSLog(@"不可删除的对象");
    }
}
 
 
#pragma mark 文件数据的写入
-(void)writeToFile:(NSString*)content path:(NSString*)path{
    NSData * data = [content dataUsingEncoding:NSUTF8StringEncoding];
    BOOL isFinish = [data writeToFile:path atomically:YES];
    if (!isFinish) {
        NSLog(@"写入失败");
    }
}
 
 
#pragma mark --  判断两个文件内容是否相等
-(void)fileContentComparison{
    /**
     测试文件内容是否相等
     */
    NSArray * contentArray = @[@"清明时节雨纷纷",@"路上行人欲断魂",@"成功QQ吧",@"成功QQ吧"];
    NSArray * fileNameArray = @[@"cg_a.txt",@"cg_b.txt",@"cg_c.txt",@"cg_d.txt"];
    /**
     创建文件,并写入数据
     */
    for (unsigned int i =0 ; i<fileNameArray.count; i++) {
        BOOL isFile = [[NSFileManager defaultManager] createFileAtPath:[self createFilePath:fileNameArray[i]] contents:contentArray[i] attributes:nil];
        if (!isFile) {
            NSLog(@"文件创建失败");
        }
    }
    /**
     进行分组比较
     */
    for (unsigned int i =0; i<fileNameArray.count; i++) {
        /**
         文件内容的比较
         @parm  path1,path2 文件的路径
         */
        if (i==0||i%2==0) {
            NSLog(@"%d",i);
            BOOL isIdentical = [[NSFileManager defaultManager] contentsEqualAtPath:[self createFilePath:fileNameArray[i]] andPath:[self createFilePath:fileNameArray[i+1]]];
            if (!isIdentical) {
                NSLog(@"文件不相同-%@--%@",fileNameArray[i],fileNameArray[i+1]);
            }else{
                NSLog(@"文件相同-%@--%@",fileNameArray[i],fileNameArray[i+1]);
            }
            /**
             输出:
             2017-03-30 15:08:04.833 NSFileManager[3899:940954] 0
             2017-03-30 15:08:04.833 NSFileManager[3899:940954] 文件不相同-cg_a.txt--cg_b.txt
             2017-03-30 15:08:04.834 NSFileManager[3899:940954] 2
             2017-03-30 15:08:04.834 NSFileManager[3899:940954] 文件相同-cg_c.txt--cg_d.txt
             */
        }
    }
}
 
 
#pragma mark -- 获取可视化文件字符串
-(void)getVisualizationFileString:(NSString*)path{
    NSString * displayNameAtPath = [[NSFileManager defaultManager] displayNameAtPath:path];
    NSLog(@"可视化串:%@",displayNameAtPath);
    /**
     输出:
     2017-03-30 15:28:27.354 NSFileManager[4108:1007542] 可视化串:NetWork小贱.plist
     2017-03-30 15:28:27.355 NSFileManager[4108:1007542] 可视化串:NetWork
     
     注意:
     该返回的可视化字符串,不可用于其他函数的参数。对于本地的文件,将返回合适的字符串。
     */
}
 
 
 
#pragma mark 文件或者文件夹的拷贝
-(void)copyFile{
    [self createFolder:@"A"];
    [self createFile:@"A/a.txt"];
    [self createFolder:@"B"];
    [self createFolder:@"B/C"];
    NSString * FloderNameStr = [self createFilePath:@"A"];
    NSString * fileNameStr = [self createFilePath:@"A/a.txt"];
    NSString * fileName = [self createFilePath:@"B/b.txt"];
    NSString * FloderName = [self createFilePath:@"C"];
    /**
     文件夹的复制
     */
    [self copyObject:FloderNameStr toPath:FloderName];
    /**
     文件的复制
     */
    [self copyObject:fileNameStr toPath:fileName];
    /**
     输出:
     NSFileManager[5178:1361817] 复制成功
     NSFileManager[5178:1361817] 复制成功
     注意:
     文件和文件夹的复制,复制文件不能提前比被复制文件存在。比如:B要复制A,那B在复制前不能存在,否则将不成功。
     */
}
-(void)copyObject:(NSString*)path toPath:(NSString*) path1 {
    /**
     文件夹的拷贝
     @parm  srcPath  要复制的文件夹路径
     @parm  dstPath  目的文件夹路径
     @parm  error    错误信息
     */
    NSError * error;
    BOOL isFolder = [[NSFileManager defaultManager] copyItemAtPath:path toPath:path1 error:&error];
    if (!isFolder) {
        NSLog(@"文件夹复制失败-%@",error);
        return;
    }
    NSLog(@"复制成功");
}
 
 
#pragma mark -- 文件和文件夹的移动
-(void)moveFile{
    /**
     文件夹的移动
     */
    [self createFolder:@"M_1"];
    NSString * Folder_M1_Path = [self createFilePath:@"M_1"];
    NSString * Folder_M2_Path = [self createFilePath:@"M_2"];
    /**
     我们要将 M_1 移动到 M_2 里面
     */
    [self moveObject:Folder_M1_Path toPath:Folder_M2_Path];
    /**
     文件的移动
     */
    [self createFile:@"m.txt"];
    NSString * filePath = [self createFilePath:@"m.txt"];
    NSString * Folder_M3_Path = [self createFilePath:@"M_3"];
    [self moveObject:filePath toPath:Folder_M3_Path];
    /**
     输出:
     2017-03-30 17:23:59.848 NSFileManager[5818:1525452] 移动成功!
     2017-03-30 17:23:59.849 NSFileManager[5818:1525452] 移动成功!
     */
}
-(void)moveObject:(NSString*)path1 toPath:(NSString*)path2{
    /**
     对象的移动
     @parm  srcPath 要移动的对象路径
     @parm  dstPath 移动后的对象路径
     @parm  error    错误信息
     */
    NSError * error ;
    BOOL isMove = [[NSFileManager defaultManager] moveItemAtPath:path1 toPath:path2 error:&error];
    if (isMove) {
        NSLog(@"移动成功!");
    }
}
 
 
#pragma mark 创建文件或文件夹间的硬链接
-(void)linkFile{
    /**
     创建文件夹
     */
    [self createFile:@"L_k_1.txt"];
    NSString * FolderPath =  [self createFilePath:@"L_k_1.txt"];
    NSString * FolderLinkPath =  [self createFilePath:@"L_k_2.txt"];
    /**
     创建链接
     */
    [self linkObject:FolderPath toPath:FolderLinkPath];
    /**
     输出:
     2017-03-30 17:56:53.320 NSFileManager[6181:1659306] 链接成功!
     */
}
-(void)linkObject:(NSString*)path1 toPath:(NSString*)path2{
    /**
     对象间创建硬链接
     @parm  srcPath 要链接的对象路径
     @parm  dstPath 链接后的对象路径
     @parm  error   错误信息
     */
    NSError * error ;
    BOOL isLink = [[NSFileManager defaultManager] linkItemAtPath:path1 toPath:path2 error:&error];
    if (isLink) {
        NSLog(@"链接成功!");
    }
    [@"my love show" writeToFile:[self createFilePath:@"L_k_2.txt"] atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    NSString * FolderLinkPath =  [self createFilePath:@"L_k_1.txt"];
    NSLog(@"%@",[NSString stringWithContentsOfFile:FolderLinkPath encoding:NSUTF8StringEncoding error:NULL]);
}
 
 
#pragma mark  -- 删除文件
-(void)removeFile{
    /**
     删除文件夹
     */
    [self createFolder:@"Love"];
    [self removeObject:[self createFilePath:@"Love"]];
    /**
     删除文件
     */
    [self createFile:@"remove.txt"];
    [self removeObject:[self createFilePath:@"remove.txt"]];
 
}
-(void)removeObject:(NSString*)path{
    /**
     检测文件是否存在
     */
    BOOL isExistence = [[NSFileManager defaultManager] fileExistsAtPath:path];
    if (isExistence) {
        NSError * error ;
        BOOL isRemove = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        if (isRemove) {
            NSLog(@"%@",@"删除成功");
        }else{
            NSLog(@"删除失败--error:%@",error);
        }
    }else{
        NSLog(@"文件不存在,请确认路径");
    }
    /**
     输出:
     2017-03-31 11:28:24.004 NSFileManager[2190:371451] 删除成功
     2017-03-31 11:28:24.007 NSFileManager[2190:371451] 删除成功
     */
}
 
 
#pragma mark -- 获取数据
-(void)getDataFile{
    BOOL isFile = [[NSFileManager defaultManager] createFileAtPath:[self createFilePath:@"abc.txt"] contents:[@"成功QQ吧" dataUsingEncoding:NSUTF8StringEncoding ] attributes:nil];
    if (isFile) {
        [self getData:[self createFilePath:@"abc.txt"]];
    }
}
-(void)getData:(NSString*)path{
    if (!path) return;
    NSData * data = [[NSFileManager defaultManager] contentsAtPath:path];
    NSString * content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"获取数据:%@",content);
}
 
 
#pragma mark --  获取文件或者文件夹的层次结构
-(void)getArrangement{
    /**
     文件夹层次
     */
    [self createFolder:@"ABC/BS/CKK/wwq"];
    [self getArrangementObject:[self createFilePath:@"ABC"]];
    /**
     输出:
     2017-03-31 15:54:00.584 NSFileManager[4859:1110472] 文件的层次:(
     BS,
     "BS/CKK",
     "BS/CKK/wwq"
     )
     
     注意:
     该方法一版不要调用,因为计算损耗较大
     */
}
-(void)getArrangementObject:(NSString*)path{
    if (!path) return;
    NSArray * array = [[NSFileManager defaultManager] subpathsAtPath:path];
    NSLog(@"文件的层次:%@",array);
}
 
 
#pragma mark --  获取文件或者文件夹在系统中代表的字符
-(void)getfileSystemRepresentation{
    /**
     创建一个文件
     */
    [self createFolder:@"SR_Love"];
    const char * ar = [[NSFileManager defaultManager] fileSystemRepresentationWithPath:[self createFilePath:@"SR_Love"]];
    NSLog(@"字符:%s",ar);
}
 
 
#pragma mark  --  获取文件属性
-(void)getFileAttribute{
    [self createFolder:@"Attribute"];
    /**
     获取路径
     */
    NSString * FolderPath = [self createFilePath:@"Attribute"];
    NSDictionary * FileAttribute = [[NSFileManager defaultManager] attributesOfItemAtPath:FolderPath error:NULL];
    NSLog(@"文件的属性:%@",FileAttribute);
    /**
     输出:
     2017-03-31 16:35:43.572 NSFileManager[5283:1231846] 文件的属性:{
     NSFileCreationDate = "2017-03-31 08:35:43 +0000";
     NSFileExtensionHidden = 0;
     NSFileGroupOwnerAccountID = 20;
     NSFileGroupOwnerAccountName = staff;
     NSFileModificationDate = "2017-03-31 08:35:43 +0000";
     NSFileOwnerAccountID = 501;
     NSFilePosixPermissions = 493;
     NSFileReferenceCount = 2;
     NSFileSize = 68;
     NSFileSystemFileNumber = 22010573;
     NSFileSystemNumber = 16777218;
     NSFileType = NSFileTypeDirectory;
     }
     
     
     介绍:
     NSFileCreationDate          文件创建的时间
     NSFileExtensionHidden       文件路径是否展开
     NSFileGroupOwnerAccountID   创建分组的ID
     NSFileGroupOwnerAccountName 创建分组的名字
     NSFileModificationDate      文件修改的时间
     NSFileOwnerAccountID        创建者的ID
     NSFilePosixPermissions      文件权限的编号
     NSFileReferenceCount        文件参考数量
     NSFileSize                  文件大小
     NSFileSystemFileNumber      系统文件编号
     NSFileSystemNumber          系统编号
     NSFileType                  文件类型
     */
}
 
 
#pragma mark  --  NSFileManagerDelegate
/**
 文件移动
 */
-(BOOL)fileManager:(NSFileManager *)fileManager shouldRemoveItemAtURL:(NSURL *)URL{
    return YES;
}
-(BOOL)fileManager:(NSFileManager *)fileManager shouldRemoveItemAtPath:(NSString *)path{
    return YES;
}
/**
 文件复制
 */
-(BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL{
    return YES;
}
-(BOOL)fileManager:(NSFileManager *)fileManager shouldCopyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    return YES;
}
/**
 文件的连接
 */
-(BOOL)fileManager:(NSFileManager *)fileManager shouldLinkItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL{
    return YES;
}
-(BOOL)fileManager:(NSFileManager *)fileManager shouldLinkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    return YES;
}
/**
 文件的移动
 */
-(BOOL)fileManager:(NSFileManager *)fileManager shouldMoveItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL{
    return YES;
}
-(BOOL)fileManager:(NSFileManager *)fileManager shouldMoveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    return YES;
}
/**
 文件移除
 */
-(BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error removingItemAtURL:(NSURL *)URL{
    return YES;
}
- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error removingItemAtPath:(NSString *)path{
    return YES;
}
/**
 文件连接错误
 */
- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error linkingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath{
    return YES;
}
- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error linkingItemAtURL:(NSURL *)srcURL toURL:(NSURL *)dstURL {
    return YES;
}

@end

上一篇 下一篇

猜你喜欢

热点阅读