iOS 沙盒目录结构和文件操作(NSFileManager)(二)

2.读取文件夹

    NSString * path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"testFile.txt"];
    NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
    NSLog(@"%@",array);

打印结果:

NSFileManager操作[3488:76713] (

    "\Ud83d\Udc02",

    "\Ud83d\Udc37"

)

六,文件操作(NSFileManager)

  1.概述

     在iOS上的文件操作和在Mac上的文件操作有些不同, 在Mac上你可以把文件放在任意的一个文件夹里面, 但是在iOS上, 我们前面已经提过,你所写的文件就只能放在三个文件夹里, 分别是Documents, Library, tmp三个文件, 这里需要注意一下, library和tmp文件会在软件升级, 系统升级或者系统空间不足时会自动清除里面的文件, 只有在Documents文件才可以永久保存, 直到你把软件删除为止.

     这里涉及的方法:
     NSHomeDirectory:这个方法的意思就是获取软件的主目录.
     stringByAooendingPathComponent:这个方法的意思就是在目录后添加一个文件.

     NSFileManager中包含了用来查询单词库目录、创建、重命名、删除目录以及获取/设置文件属性的方法(可读性,可编写性等等)。

  2.初始化

NSFileManager的用两种形式,

第一种

NSFileManager *fm = [NSFileManager defaultManager];

   使用defaultManager的时候,实际上获取的是一个单例(同一个对象),绝大多数时候,使用这个就可以了。 

第二种

NSFileManager *fileManager = [[NSFileManager alloc]init];

   如果在不同线程中使用,而且需要代理函数来监听事件,这时候要使用init来创建每个线程独立的fileManager

3.常见的NSFileManager方法及相关方法

1>常见的NSFileManager处理文件的方法

-(NSData *)contentsAtPath:path  //从一个文件读取数据
-(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr  //向一个文件写入数据
-(BOOL)removeItemAtPath:path error:err  //删除一个文件
-(BOOL)moveItemAtPath:from toPath:to error:err  //重命名或者移动一个文件(to不能是已存在的)
-(BOOL)copyItemAtPath:from toPath:to error:err  //复制文件(to不能是已存在的)
-(BOOL)contentsEqualAtPath:path andPath:path2  //比较两个文件的内容
-(BOOL)fileExistAtPath:path  //测试文件是否存在
-(BOOL)isReadableFileAtPath:path  //测试文件是否存在,并且是否能执行读操作  
-(BOOL)isWriteableFileAtPath:path  //测试文件是否存在,并且是否能执行写操作  
-(NSDictionary *)attributesOfItemAtPath:path error:err  //获取文件的属性  
-(BOOL)setAttributesOfItemAtPath:attr error:err  //更改文件的属性

2>常见的NSFileManager处理目录的方法

-(NSString *)currentDirectoryPath  //获取当前目录
-(BOOL)changeCurrentDirectoryPath:path  //更改当前目录
-(BOOL)copyItemAtPath:from toPath:to error:err  //复制目录结构(to不能是已存在的)
-(BOOL)createDirectoryAtPath:path withIntermediateDirectories:(BOOL)flag attribute:attr  //创建一个新目录
-(BOOL)fileExistAtPath:path isDirectory:(BOOL*)flag  //测试文件是不是目录(flag中储存结果YES/NO)
-(NSArray *)contentsOfDirectoryAtPath:path error:err  //列出目录内容
-(NSDirectoryEnumerator *)enumeratorAtPath:path  //枚举目录的内容
-(BOOL)removeItemAtPath:path error:err  //删除空目录
-(BOOL)moveItemAtPath:from toPath:to error:err   //重命名或移动一个目录(to不能是已存在的)

3>管理路径方法 @interface NSString (NSStringPathExtensions)

+(NSString *)pathWithComponens:components  //根据components中的元素构造有效路径
-(NSArray *)pathComponents  //析构路径,获得组成此路径的各个部分
-(NSString *)lastPathComponent  //提取路径的最后一个组成部分
-(NSString *)pathExtension  //从路径的最后一个组成部分中提取其扩展名
-(NSString *)stringByAppendingPathComponent:path  //将path添加到现有路径的末尾
-(NSString *)stringByAppendingPathExtension:ext  //将指定的扩展名添加到路径的最后一个组成部分
-(NSString *)stringByDeletingLastPathComponent  //删除路径的最后一个组成部分
-(NSString *)stringByDeletingPathExtension  //从文件的最后一部分删除扩展名
-(NSString *)stringByExpandingTileInPath   //将路径中代字符扩展成用户主目录(~)或指定用户的主目录(~user)
-(NSString *)stringByresolvingSymlinksInPath  //尝试解析路径中的符号链接
-(NSString *)stringByStandardizingPath  //通过尝试解析~、..(父目录符号)、.(当前目录符号)和符号链接来标准化路径

4>常用函数工具

NSString* NSUserName(void)  //返回当前用户的登录名
NSString* NSFullUserName(void)  //返回当前用户的完整用户名
NSString* NSHomeDirectory(void)  //返回当前用户主目录的路径
NSString* NSHomeDirectoryForUser(NSString* user)  //返回用户user的主目录
NSString* NSTemporaryDirectory(void)  //返回可用于创建临时文件的路径目录

示例:

NSString * homePath =NSHomeDirectory();

4.相关常规的用法

    1>获取文件路径

     - (NSString *)getDocumentsPath{
       //获取Documents路径
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [paths objectAtIndex:0];
        NSLog(@"path:%@", path);
        return path;
     }
   2>创建文件夹

    方法:

 - (BOOL)createDirectoryAtPath:(NSString *)path withIntermediateDirectories:(BOOL)createIntermediates attributes:(NSDictionary *)attributes error:(NSError **)error
    示例:

  -(void)createDirectory{
      NSString *documentsPath =[self getDocumentsPath];
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSString *iOSDirectory = [documentsPath stringByAppendingPathComponent:@"iOS"];
      BOOL isSuccess = [fileManager createDirectoryAtPath:iOSDirectory withIntermediateDirectories:YES attributes:nil error:nil];
      if (isSuccess) {
         NSLog(@"success");
      } else {
         NSLog(@"fail");
      }
  }
   3>创建文件

    方法:

   - (BOOL)createFileAtPath:(NSString *)path contents:(NSData *)contents attributes:(NSDictionary *)attributes
    示例:

 -(void)createFile{
     NSString *documentsPath =[self getDocumentsPath];
     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
     BOOL isSuccess = [fileManager createFileAtPath:iOSPath contents:nil attributes:nil];
     if (isSuccess) {
        NSLog(@"success");
     } else {
        NSLog(@"fail");
     }
 }
   4>写文件

  方法:

  -(BOOL)createFileAtPath: path contents:(NSData *)data attributes:attr  //向一个文件写入数据

  示例:

  -(void)writeFile{
     NSString *documentsPath =[self getDocumentsPath];
     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
     BOOL isSuccess = [fileManager createFileAtPath:iOSPath contents:nil/* NSData* */ attributes:nil];
     if (isSuccess) {
        NSLog(@"write success");
     } else {
        NSLog(@"write fail");
     }
 }

  5>读取文件内容

  方法:

  -(NSData *)contentsAtPath:path  //从一个文件读取数据

  示例:

 //读取文件内容
 -(void)readFileContent{
     NSString *documentsPath =[self getDocumentsPath];
     NSFileManager *fileManager = [NSFileManager defaultManager];
     NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
     NSData * data = [fileManager contentsAtPath:iOSPath];
     NSLog(@"data:%@",data);
 }
  6>判断文件是否存在

  方法:

 - (BOOL)fileExistsAtPath:(NSString *)path

  示例:

  - (BOOL)isSxistAtPath:(NSString *)filePath{
     NSFileManager *fileManager = [NSFileManager defaultManager];
     BOOL isExist = [fileManager fileExistsAtPath:filePath];
     return isExist;
 }
  7>计算文件大小

  方法:

  - (NSDictionary*)attributesOfItemAtPath:(NSString *)path error:(NSError **)error;
  @interface NSDictionary<KeyType, ObjectType> (NSFileAttributes)
  - (unsigned long long)fileSize;
  - (nullable NSDate *)fileModificationDate;
  - (nullable NSString *)fileType;
  - (NSUInteger)filePosixPermissions;
  - (nullable NSString *)fileOwnerAccountName;
  - (nullable NSString *)fileGroupOwnerAccountName;
  - (NSInteger)fileSystemNumber;
  - (NSUInteger)fileSystemFileNumber;
  - (BOOL)fileExtensionHidden;
  - (OSType)fileHFSCreatorCode;
  - (OSType)fileHFSTypeCode;
  - (BOOL)fileIsImmutable;
  - (BOOL)fileIsAppendOnly;
  - (nullable NSDate *)fileCreationDate;
  - (nullable NSNumber *)fileOwnerAccountID;
  - (nullable NSNumber *)fileGroupOwnerAccountID;
  @end

 示例:

- (unsigned long long)fileSizeAtPath:(NSString *)filePath{
     NSFileManager *fileManager = [NSFileManager defaultManager];
     BOOL isExist = [fileManager fileExistsAtPath:filePath];
     if (isExist){
         unsigned long long fileSize = [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
         return fileSize;
     } else {
         NSLog(@"file is not exist");
         return 0;
     }
 }
 8>计算整个文件夹中所有文件大小 
- (unsigned long long)folderSizeAtPath:(NSString*)folderPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:folderPath];
    if (isExist){
        NSEnumerator *childFileEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
        unsigned long long folderSize = 0;
        NSString *fileName = @"";
        while ((fileName = [childFileEnumerator nextObject]) != nil){
            NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        return folderSize / (1024.0 * 1024.0);
    } else {
        NSLog(@"file is not exist");
        return 0;
    }
}
9>删除文件

方法:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

示例:

-(void)deleteFile{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *iOSPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager removeItemAtPath:iOSPath error:nil];
    if (isSuccess) {
        NSLog(@"delete success");
    }else{
        NSLog(@"delete fail");
    }
}
10>移动文件

方法:

- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

示例:

- (void)moveFileName{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
        NSLog(@"rename success");
    }else{
        NSLog(@"rename fail");
    }
}

11.复制文件

方法:

- (BOOL)copyItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

示例:

-(void)copyTheFile{
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    BOOL isSuccess = [fileManager copyItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
        NSLog(@"rename success");
    }else{
        NSLog(@"rename fail");
    }
}
12>重命名

涉及方法:

- (BOOL)moveItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath error:(NSError **)error

示例:

- (void)renameFileName{
    //通过移动该文件对文件重命名
    NSString *documentsPath =[self getDocumentsPath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"iOS.txt"];
    NSString *moveToPath = [documentsPath stringByAppendingPathComponent:@"rename.txt"];
    BOOL isSuccess = [fileManager moveItemAtPath:filePath toPath:moveToPath error:nil];
    if (isSuccess) {
        NSLog(@"rename success");
    }else{
        NSLog(@"rename fail");
    }
}
13.浅度遍历目录

方法:

- (NSArray *)contentsOfDirectoryAtPath:(NSString *)path error:(NSError **)error

示例:

-(NSArray*)shallowTraversalDirectory{
    NSString * documentPath = [self getDocumentsPath];
    NSFileManager *fileManager =[NSFileManager defaultManager];
    NSArray * array =[fileManager contentsOfDirectoryAtPath:documentPath error:nil];
    NSLog(@"array:%@",array);
    return array;
}

14.深度遍历目录

方法:

- (NSArray *)subpathsOfDirectoryAtPath:(NSString *)path error:(NSError **)error

示例:

-(NSArray*)depthOfTheDirectoryTraversal{
    NSString * documentPath = [self getDocumentsPath];
    NSFileManager *fileManager =[NSFileManager defaultManager];
    NSArray * array =[fileManager subpathsOfDirectoryAtPath:documentPath error:nil];
    NSLog(@"array:%@",array);
    return array;
}



  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值