iOS开发笔记之NSFileManager的使用

来源:互联网 发布:魔兽世界网络卡 编辑:程序博客网 时间:2024/05/16 12:02

  对于文件的管理,从项目需求中出发,有如下的学习成果。查看文档基本能完成基本的需求。

  文档中部分常用的方法:(基本基于path和URL成对存在,这里主要解读关于path的)
  
  //获取单例
  + (NSFileManager *)defaultManager; 
  
  //创建文件夹 
  @param path 要创建文件夹的路径
  @param createIntermediates 是否创建中间文件夹 经过实验发现 如 @"/Users/plyn/Desktop/实验4/shiyan" 路径中/实验4/shiyan本来是不存在的 如果这个参数是YES则可以成功地创建这个路径地文件夹;如果传NO则无法创建
  @param attribute 创建文件夹属性  传nil地话系统会自动创建
  @param error 错误信息
  - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error NS_AVAILABLE(10_5, 2_0);


  //获取文件夹里面的文件名,有两个方法:
    第一个非递归的returns an NSArray of NSStrings representing the filenames of the items in the specified directory
  - (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
    第二个递归的,及返回子文件夹的子文件名returns an NSArray of NSStrings representing the filenames of the items in the specified directory and all its subdirectories recursively
  - (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
 
  //获取文件夹的属性
  - (NSDictionary *)attributesOfItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
  可通过以下方法获取相关属性
  @interface NSDictionary (NSFileAttributes)


 - (unsigned long long)fileSize;        //文件大小
 - (NSDate *)fileModificationDate;      //文件的修改时间
 - (NSString *)fileType;                //文件类型
 - (NSUInteger)filePosixPermissions;
 - (NSString *)fileOwnerAccountName;    //文件拥有者
 - (NSString *)fileGroupOwnerAccountName;
 - (NSInteger)fileSystemNumber;       
 - (NSUInteger)fileSystemFileNumber;
 - (BOOL)fileExtensionHidden;
 - (OSType)fileHFSCreatorCode;
 - (OSType)fileHFSTypeCode;
 - (BOOL)fileIsImmutable;
 - (BOOL)fileIsAppendOnly;
 - (NSDate *)fileCreationDate;        //创建时间
 - (NSNumber *)fileOwnerAccountID;
 - (NSNumber *)fileGroupOwnerAccountID;
  
  其他一些常用的方法
  //拷贝文件
 - (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
  //移动
 - (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
  //连接?还要查查
 - (BOOL)linkItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
  //删除
 - (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error NS_AVAILABLE(10_5, 2_0);
以上四个方法均有其对应触发的NSFileManagerDelegate


  几个常用判断
  //文件是否存在
 - (BOOL)fileExistsAtPath:(NSString *)path;
  //文件是都存在 是都是文件夹
 - (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory;
  //是否可读
 - (BOOL)isReadableFileAtPath:(NSString *)path;
  //是否可写
 - (BOOL)isWritableFileAtPath:(NSString *)path;
  //是否是可执行文件
 - (BOOL)isExecutableFileAtPath:(NSString *)path;
 //是否可删除
 - (BOOL)isDeletableFileAtPath:(NSString *)path;
  
  


1常用的沙盒路径路径
+(NSString *)docmentPath{
    NSString *path=[[NSString alloc]init];
    path=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
    return path;
}


+(NSString *)cachePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    return path;
}


+(NSString *)libraryPath{
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    return path;
    
}


2.创建文件夹
  @param baseDir 主路径 
  @param folder 要创建的文件名
+(BOOL)creatFileFolderInBaseDirectory:(NSString*)baseDir WithFloderName:(NSString*)folder{
    NSString *path = [NSString stringWithFormat:@"%@/%@", baseDir, folder];
    BOOL isDir = NO;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:path isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) )
    {
        return[fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }else return YES;
}


3.文件写入的方法
 <1>使用底层方法
    FILE *pFile = fopen(strDestPath.c_str(), "wb");
    if(pFile != NULL)
    {
        fwrite(&pszUnitBuf[4], sizeof(unsigned char), nSrcSize - 4, pFile);
        fclose(pFile);
        errCode = ERR_NORMAL;
    }
<2>先将文件转为 NSData 再 writeToFile
   NSError *error;
   NSData *data =[NSData dataWithContentsOfFile:@"/Users/plyn/Desktop/annet_login_bg.png"];
   NSString *path1=[NSString stringWithFormat:@"/Users/plyn/Desktop/实验/dd%d.png",i];
   BOOL y=[data writeToFile:path1 options:0 error:&error];




4.获取文件或文件夹大小
 @param folderPath文件夹路径
+(float)getSizeOfFolder:(NSString*)folderPath{
    unsigned long long folderSize=0;
    NSFileManager * manager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    //判断folderPath 文件是否存在 是否是文件夹
    if ([manager fileExistsAtPath:folderPath isDirectory:&isDir]) {
        if (isDir) {
            //获取所有子文件名
            NSArray * subPathArr = [manager subpathsAtPath:folderPath];
            //遍历
            for (NSString * subPath in subPathArr) {
                //排除隐藏文件.DS_Store
                if ([subPath hasPrefix:@"."]) {
                    continue;
                }
                //拼接路径
                NSString *path =[folderPath stringByAppendingPathComponent:subPath];
                if ([manager fileExistsAtPath:path isDirectory:&isDir]) {
                    if (isDir) {
                        //如果里面还是文件夹的 递归本方法
                        [PFTool getSizeOfFolder:path];
                    }else{
                        //如果不是 获取文件属性 其中 NSFileSize 是获取文件大小
                        NSDictionary *dic = [manager attributesOfItemAtPath:path error:nil];
                        if (dic) {
                            folderSize +=[dic[@"NSFileSize"] unsignedLongLongValue];
                        }
                    }
                }
            }
            
        }else{
            //如果开始就不是文件夹,直接取文件大小
            NSDictionary *dic = [manager attributesOfItemAtPath:folderPath error:nil];
            if (dic) {
                folderSize +=[dic[@"NSFileSize"] unsignedLongLongValue];
            }
            
        }
    }
    //对比一下mac里面的文件大小,好像是除以1000而不是1024,所以跟着苹果走
    return (float)folderSize/(1000*1000);
}


5.实现文件夹存储大小的动态平衡
  按文件修改时间的顺序排序,每次删除指定大小的文件 删除最早时间的
  先调用+getSizeOfFolder: 获取文件夹大小 判断超出多少容量后删除多少
  @param fileSize 要删除多少
  @param folderPath 文件夹路径 绝对路径
+(BOOL)deleteFileSize:(float)fileSize  fromFolder:(NSString*)folderPath{
    __block float folderSize=0;
    NSFileManager * manager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    if ([manager fileExistsAtPath:folderPath isDirectory:&isDir]) {
        
        if (isDir) {
            NSArray * subPathArr = [manager subpathsAtPath:folderPath];
            NSLog(@"%@",subPathArr);
            
            NSMutableArray *pathArr =[NSMutableArray array];
            for (int i=0; i<subPathArr.count; i++) {
                if ([subPathArr[i] hasPrefix:@"."]) {
                    continue;
                }
                
                [pathArr addObject:[folderPath stringByAppendingPathComponent:subPathArr[i]]];
            }
            //            NSLog(@"%@",pathArr);
            //按修改时间排序
            [pathArr sortUsingComparator:^NSComparisonResult(NSString * obj1, NSString* obj2) {
                NSDictionary *dic1 = [manager attributesOfItemAtPath:obj1 error:nil];
                NSTimeInterval dateF1 = [[dic1 fileModificationDate] timeIntervalSince1970];
                NSDictionary *dic2 = [manager attributesOfItemAtPath:obj2 error:nil];
                NSTimeInterval dateF2 = [[dic2 fileModificationDate] timeIntervalSince1970];
                
                if (dateF1> dateF2) {
                    return NSOrderedDescending;
                }else if (dateF1 == dateF2){
                    return NSOrderedSame;
                }else{
                    return NSOrderedAscending;
                }
            }];
            NSLog(@"%@",pathArr);
            //按排序删除文件 直到删除达到指定大小
            [pathArr enumerateObjectsUsingBlock:^(NSString* obj, NSUInteger idx, BOOL *stop) {
                NSDictionary *dic1 = [manager attributesOfItemAtPath:obj error:nil];
                folderSize += (float)[dic1 fileSize]/(1000*1000);
                [manager removeItemAtPath:obj error:nil];
                
                if (folderSize>fileSize) {
                    *stop =YES;
                }
            }];
            
            return YES;
            
        }else{
            
            return NO;
        }
    }else return NO;
    

}


6.设置文件的属性 ,如配合上面的方法设置最后的修改时间以达到以最后阅读时间排序的效果

+(BOOL)setModificationDateForFile:(NSString*)path{
    NSDictionary *setDic =[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate];
   return  [[NSFileManager defaultManager] setAttributes:setDic ofItemAtPath:path error:nil];
}




0 0
原创粉丝点击