Swift&OC 文件夹和文件的详细操作

建议大家看 JKSwiftExtension,测试用例在 FileManagerExtensionViewController ,是关于沙盒的操作
在iOS开发我们会遇到文件、音频、视频等等下载后本地存储的情况,这时对读文件,写文件就显得很重要,对文件夹以及文件中的文件的操作,这时就可以使用NSFileManager(FileManager)或NSFileHandle(FileHandle)来实现。下面会用OC和Swift的对比来实现对文件和文件夹的操作

  • 文件管理器(NSFileManager/FileManager):此类主要是对文件进行的操作(创建/删除/改名等)以及文件信息的获取。
  • 文件连接器(NSFileHandle/FileHandle):此类主要是对文件内容进行读取和写入操作。

一、沙盒以及组成部分

iOS应用程序只能对自己创建的文件系统读取文件,这个"独立","封闭","安全"的空间,称之为沙盒。

  • 1.1、Home目录(应用程序包)
    • 整个应用程序各文档所在的目录,包含了所有的资源文件和可执行文件
  • 1.2、Documents
    • 保存应用运行时生成的需要持久化的数据,iTunes同步设备时会备份该目录
    • 需要保存由"应用程序本身"产生的文件或者数据,例如: 游戏进度,涂鸦软件的绘图
    • 目录中的文件会被自动保存在 iCloud
    • 注意: 不要保存从网络上下载的文件,否则会无法上架!
  • 1.3、tmp
    • 保存应用运行时所需要的临时数据或文件,"后续不需要使用",使用完毕后再将相应的文件从该目录删除。
    • 应用没有运行,系统也可能会清除该目录下的文件
    • iTunes不会同步备份该目录
    • 重新启动手机, tmp 目录会被清空
    • 系统磁盘空间不足时,系统也会自动清理
  • 1.4、Library/Cache
    • 保存应用运行时生成的需要持久化的数据,iTunes同步设备时不备份该目录。一般存放体积大、不需要备份的非重要数据
    • 保存临时文件,"后续需要使用",例如: 缓存的图片,离线数据(地图数据)
    • 系统不会清理 cache 目录中的文件
    • 就要求程序开发时, "必须提供 cache 目录的清理解决方案"
  • 1.5、Library/Preference
    • 保存应用的所有偏好设置,IOS的Settings应用会在该目录中查找应用的设置信息。iTunes
    • 用户偏好,使用 NSUserDefault 直接读写!
    • 如果想要数据及时写入硬盘,还需要调用一个同步方法 synchronize()
  • 1.6.程序.app,与另三个路径的父路径不同
    • 这是应用程序的程序包目录,包含应用程序的本身。由于应用程序必须经过签名,所以您在运行时不能对这个目录中的内容进行修改,否则可能会使应用程序无法启动

二、对文件以及文件夹的操作

2.1、获取各个目录的路径
  • 2.1.1、HomeDirectory

    OC:                
    NSString *filePath = NSHomeDirectory();
    Swift:
    let homePath = NSHomeDirectory()
    
  • 2.1.2、Documents

    OC:                
    方法一
    NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0]; 
    方法二
    NSString * documentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    Swift:
    方法1
    let documentsPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let documentsPath = documentPaths[0]
    方法2
    let documentsPath = NSHomeDirectory()+"/Documents"
    
  • 2.1.3、Caches

    OC:  
    方法一
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    方法二
    NSString *cachesPath= [NSHomeDirectory() stringByAppendingPathComponent:@"/Library/Caches"];             
    Swift:
    方法1
    let cachePaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let cachePath = cachePaths.last
    方法2
    let cachePath = NSHomeDirectory()+"/Library/Caches"
    
  • 2.1.4、Library

    OC:  
    方法一
    NSString * libraryPath = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    方法二
    NSString * libraryPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Library"];
    Swift:
    方法1
    let libraryPaths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
    let libraryPath = libraryPaths[0]
    方法2
    let libraryPath = NSHomeDirectory()+"/Library"
    
  • 2.1.5、tmp

    OC:  
    方法一
    NSString *tempPath = NSTemporaryDirectory();
    方法二
    NSString * tempPath = [NSHomeDirectory() stringByAppendingPathComponent:@"/tmp"];
    Swift:
    方法1
    let tempPath = NSTemporaryDirectory()
    方法2
    let tempPath = NSHomeDirectory()+"/tmp"
    
2.2、根据传件来的路径创建文件夹 创建文件目录(蓝色的,文件夹和文件是不一样的)

应用程序目录, Caches、Library、Documents目录文件夹下创建文件夹(蓝色的)
下面以Documents为例创建JKFile为例


以Documents为例创建JKFile为例
  • OC

    NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/JKFile"];
    - (NSString *)jKCreateDir:folderName{
    
        NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent: folderName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = NO;
        // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
        BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
        if ( !(isDir == YES && existed == YES) ) {
    
          // 不存在的路径才会创建
          [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        }
      return filePath;
    }
    
  • Swift:

    let jKFilePath = NSHomeDirectory() + "/Documents/JKFile";
    func jKCreateFolder(folderName: NSString) -> NSString {
       let fileManager: FileManager = FileManager.default
       let filePath = "\(folderName)"
       let exist = fileManager.fileExists(atPath: filePath)
       // 不存在的路径才会创建
       if (!exist) {
    
        //withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
        try! fileManager.createDirectory(atPath: filePath,withIntermediateDirectories: true, attributes: nil)
        }
      return filePath as NSString
     }
    
2.3、删除文件夹(先判断文件夹存不存在)
  • OC

    NSString *filePath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/JKFile"];
    - (void)jKRemovefolder:(NSString *)filePathName {
        // filePath: 文件/目录的路径
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [NSString stringWithFormat:@"%@",filePathName];
        BOOL isDir = NO;
        // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
        BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
        if ( !(isDir == YES && existed == YES) ) {
          // 不存在的路径才会创建
          return;
        }
       //文件夹
       [fileManager removeItemAtPath:filePath error:nil];
    }
    
  • Swift:

    let jKFilePath = NSHomeDirectory() + "/Documents/JKFile";
    func jKRemovefolder(folderName: NSString){
       let fileManager: FileManager = FileManager.default
       let filePath = "\(folderName)"
       let exist = fileManager.fileExists(atPath: filePath)
       // 查看文件夹是否存在,如果存在就直接读取,不存在就直接反空
       if (exist) {
        
          try! fileManager.removeItem(atPath: filePath)
        
       }else{
        
         // 不存在就不做什么操作了
       }
    }
    
2.4、删除文件
  • OC

    - (void)jKRemovefile:(NSString *)filePathName {
         // filePath: 文件/目录的路径
         NSFileManager *fileManager = [NSFileManager defaultManager];
         NSString *filePath = [NSString stringWithFormat:@"%@",filePathName];
        //移除文件
       [fileManager removeItemAtPath:filePath error:nil];
    }
    
  • Swift:

    func jKRemovefile(folderName: NSString){
       let fileManager: FileManager = FileManager.default
       let filePath = "\(folderName)"
       //移除文件
       try! fileManager.removeItem(atPath: filePath)
     }
    
2.5、深度遍历(搜索文件夹)
  • 2.5.1、深度搜索遍历一(subpathsAtPath)深度遍历,会递归遍历子文件夹(包括符号链接,所以要求性能的话用enumeratorAtPath)


    获取某个文件下的所有文件的名字
    • OC

      NSString *filePath = NSHomeDirectory();
      -(NSArray *)jKGetAllFileNames:(NSString *)folderName
      {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        // 取得一个目录下得所有文件名
        NSArray *files = [fileManager subpathsAtPath:[self jKCreateFolder:folderName]];
        //NSLog(@"pdf名字的数量=%ld 数组=%@",files.count,files);
      
        return files;
      }
      
  • Swift:

    let jKFilePath = NSHomeDirectory();
    func jKGetAllFileNames(folderName: NSString) -> NSArray{
    
      let filePath = "\(folderName)"
      let exist = fileManager.fileExists(atPath: filePath)
      // 查看文件夹是否存在,如果存在就直接读取,不存在就直接反空
      if (exist) {
         let subPaths = fileManager.subpaths(atPath: folderName as String)
          return subPaths! as NSArray
      }else{
          return []
      }
    }
    
  • 2.5.2、深度遍历二,会递归遍历子文件夹(但不会递归符号链接)

    • OC

      // folderNmae:文件夹的名字
      -(NSArray *)jKDeepSearchEnumeratorAllFileNames:(NSString *)folderName{
      
          NSFileManager *fileManager = [NSFileManager defaultManager];
          // 取得一个目录下得所有文件名
          NSDirectoryEnumerator *files = [fileManager enumeratorAtPath:[self jKCreateFolder:folderName]];
          //NSLog(@"pdf名字的数量=%ld 数组=%@",files.count,files);
          return files.allObjects;
       }
      
    • Swift:

      func jKDeepSearchAllFiles(folderName: NSString) -> NSArray
      {
          let filePath = "\(folderName)"
          let exist = fileManager.fileExists(atPath: filePath)
          // 查看文件夹是否存在,如果存在就直接读取,不存在就直接反空
          if (exist) {
             let contentsOfPathArray = fileManager.enumerator(atPath: filePath)
             return contentsOfPathArray!.allObjects as NSArray
          }else{
             return []
          }
      }
      
2.6、对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表(只寻找一层)
读取指定目录路径下的文件、子目录及符号链接的列表(只寻找一层)
  • OC

    /**对指定路径执行浅搜索,返回指定目录路径下的文件、子目录及符号链接的列表(只寻找一层)*/
       
    NSString *customPath = [NSString stringWithFormat:@"%@",[JKFilePathOperationExtension jKHomeDirectory]];
    -(NSArray *)jKShallowSearchAllFiles:(NSString *)filePath{
    
         NSFileManager *fileManager = [NSFileManager defaultManager];
         NSArray *contentsOfPathArray = [fileManager contentsOfDirectoryAtPath:filePath error:nil];
         return contentsOfPathArray;
     }
    
  • Swift:

     /** 对指定路径执行浅搜索,读取指定目录路径下的文件、子目录及符号链接的列表(只寻找一层)*/
    let jKFilePath = NSHomeDirectory()
    func jKShallowSearchAllFiles(folderName: NSString) -> NSArray {
     
        let filePath = "\(folderName)"
        let contentsOfPathArray = try! fileManager.contentsOfDirectory(atPath: filePath);
        return contentsOfPathArray as NSArray
     
     }
    
2.7、判断文件或文件夹是否存在
  • OC

    +(BOOL)jkJudgeFileOrFolderExists:(NSString *)filePathName{
    
       NSFileManager *fileManager = [NSFileManager defaultManager];
       NSString *filePath = [NSString stringWithFormat:@"%@",filePathName];
       BOOL isDir = NO;
       // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
       BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
       if ( !(isDir == YES && existed == YES) ) {
    
            // 不存在的路径
            return NO;
       }else{
    
           return YES;
       }
      return nil;
    }
    
  • Swift:

     func jkJudgeFileOrFolderExists(folderName: NSString) -> Bool
     {
        let filePath = "\(folderName)"
        let exist = fileManager.fileExists(atPath: filePath)
        // 查看文件夹是否存在,如果存在就直接读取,不存在就直接反空
        if (exist) {
           return true
        }else{
          return false
        }
     }
    
2.8、创建文件(如:动画乐园.text格式的文本文件)
创建文件(如:动画乐园.text格式的文本文件)
  • OC

    /**folderNmae:文件的名字*/
    - (NSString *)jKCreateFile:(NSString *)folderName{
    
        NSString *filePath = [NSString stringWithFormat:@"%@",folderName];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isDir = NO;
        // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
        BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
        if ( !(isDir == YES && existed == YES) ) {
      
             // 不存在的路径才会创建
             [fileManager createFileAtPath:filePath contents:nil attributes:nil];
         }
       return filePath;
    }
    
  • Swift:

     // fileName:文件的名字(不是文件夹)
     // baseFilePath: 文件的基础路径
     // content: 存进文件的内容
     /** 根据传件来的路径创建文件*/
     func jKCreateFile(fileName: NSString,baseFilePath: NSString) -> (filePath: NSString,createStatus: Bool) {
      
       // NSHomeDirectory():应用程序目录
       let filePath = "\(baseFilePath)" + "/\(fileName)"
       let exist = fileManager.fileExists(atPath: filePath)
       // 不存在的文件路径才会创建
       if (!exist) {
          
           //withIntermediateDirectories为ture表示路径中间如果有不存在的文件夹都会创建
           let createSuccess = fileManager.createFile(atPath: filePath,contents:nil,attributes:nil)
           return (filePath as NSString,createSuccess as Bool)
          
        }
       return (filePath as NSString,true)
     }
    
2.9、可以通过write(to:)方法,可以创建文件并将对象(文件,音频,图片,视频以及数组,字典)都可以写入文件
  • 简单对象:iOS中提供四种类型可以直接进行文件存取:NSString(字符串)、NSArray(数组)、NSDictionary(字典)、NSData(数据)(以上类型包括子类)

  • 注意:数组(可变与不可变)和字典(可变与不可变)中元素对象的类型,也必须是上述四种,否则不能直接写入文件

  • 2.9.1、把NSSString保存到上面“动画乐园.text”的文件里面


    NSSString保存到上面“动画乐园.text”的文件里面
    • OC

      // 文件的路径(以文件存在为基础,创建文件请看2.9)
      NSString * path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/动画乐园.text"];
      NSString *content = @"动画乐园欢迎你"
      // 内容写入
      [content writeToFile: path atomically:YES encoding:NSUTF8StringEncoding error:nil];
      
    • Swift:

      let path = NSHomeDirectory() + "/Documents/动画乐园.text"
      let info = "动画乐园欢迎你" as String
      try! info.write(toFile: path, atomically: true, encoding: String.Encoding.utf8)
      
  • 2.9.2、把本地图片或者网络图片保存到上面“图片”的文件夹里面
    filePath图片的路径是提前存在的(没有的话看上面的去创建文件夹)

    把本地图片或者网络图片保存到上面**“图片”**的文件夹里面

    • OC

      // 本地图片的名字
      NSString *imageString = @"testimage.png";
      UIImage *image = [UIImage imageNamed:imageString];
      NSData *data = UIImagePNGRepresentation(image);
      // 图片的存储文件夹
      NSString *customPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/图片"];
      // 图片的存储路径
      imagePath = [NSString stringWithFormat:@"%@/%@", customPath, imageString];
      [data writeToFile: imagePath atomically:YES];
      
      网络图片
      NSString *imageStr = @"http://images.ciotimes.com/o_1can10mm91sd91c6n1thv15oel8g9.png";
      NSString *customPath = [NSString stringWithFormat:@"%@/%@",[JKFilePathOperationExtension jKDocuments],@"jk.png"];
      NSData *data = [NSData dataWithContentsOfURL:[NSURL  URLWithString:imageStr]];
      //转换为图片保存到以上的沙盒路径中
      UIImage * currentImage = [UIImage imageWithData:data];
      //其中参数0.5表示压缩比例,1表示不压缩,数值越小压缩比例越大
      [UIImageJPEGRepresentation(currentImage, 0.5) writeToFile:customPath  atomically:YES];
      
    • Swift:

      let filePath = NSHomeDirectory() + "/Documents/图片/testimage.png"
      let image = UIImage(named: "testimage.png")
      let data:Data = UIImagePNGRepresentation(image!)!
      try? data.write(to: URL(fileURLWithPath: filePath))
      
  • 2.9.3、把本数组写到文件里面(array.plist的文件是已经存在的基础上)


    把本数组写到文件里面(array.plist的文件是已经存在的基础上)
    • OC

      // 创建数组
      NSArray  *array = @[@"1",@"2",@"3"];
      // 文件路径(前提是已经存在),创建文件请看上面2.9
      NSString *customPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/array.plist"];
      [array writeToFile:filePath atomically:YES];
      
    • Swift

      let filePath = NSHomeDirectory() + "/Documents/array.plist"
      let array = NSArray(objects: "我","❤️","你")
      array.write(toFile: filePath, atomically: true)
      
  • 2.9.4、把本字典写到文件里面(dictionary.plist的文件是已经存在的基础上)


    把本字典写到文件里面(dictionary.plist的文件是已经存在的基础上)
    • OC

      NSString *customPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/dictionary.plist"];
      // 创建字典
      NSDictionary *dict = @{@"1":@"9",@"2":@"8",@"3":@"7",@"4":@"6"};
      dict.write(toFile: filePath, atomically: true)
      
    • Swift

      let filePath = NSHomeDirectory() + "/Documents/dictionary.plist"
      let dictionary = NSDictionary(dictionary: ["name":"JK","age":"26"])
      dictionary.write(toFile: filePath, atomically: true)
      
2.10、复制文件
复制文件
  • OC

     NSString *fromPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/我的笔记.text"];
     NSString *toPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/复制后的笔记.text"];
     NSFileManager *fileManager = [NSFileManager defaultManager];
     BOOL isCopySuccess = [fileManager copyItemAtPath: fromPath toPath: toPath error:nil];
    
  • Swift

     let homeDirectory = NSHomeDirectory()
     let fomePath = homeDirectory + "/Documents/我的笔记.text"
     let toPath = homeDirectory + "/Documents/复制后的笔记.text"
     let fileManager1 = FileManager.default
     try! fileManager1.copyItem(atPath: fomePath as String, toPath: toPath as String)
    
2.11、移动文件或者文件夹

文件夹或者文件,这里是文件夹JKPdf要提前建好,创建方式看上面

移动文件或者文件夹

  • OC

    NSString *fromPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/Documents/JKPdf"];
    NSString *toPath = [NSString stringWithFormat:@"%@%@",NSHomeDirectory(),@"/tmp/JKPdf"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isMoveSuccess = [fileManager moveItemAtPath:fromPath toPath:toPath error:nil];
    
  • Swift

    let fomePath =NSHomeDirectory()  + "/Documents/JKPdf"
    let toPath =  NSHomeDirectory()  + "/tmp/JKPdf"
    let fileManagerMove = FileManager.default
    try! fileManagerMove.moveItem(atPath: fromUrl as String, toPath: toUrl as String)
    
2.12、读取文件
  • 2.12.1、文件的类型为文本,如 我的笔记.text

    • OC

       // 拿到我的笔记.text的路径
       NSString *customPath = @"路径";
       // 取出文本的内容
       NSString *str = [NSString stringWithContentsOfFile:customPath encoding:NSUTF8StringEncoding error:nil];
      
    • Swift

       let path = NSHomeDirectory() + "/Documents/我的笔记.text"
       let readHandler =  FileHandle(forReadingAtPath: path)
       let data = readHandler?.readDataToEndOfFile()
       let readString = String(data: data!, encoding: String.Encoding.utf8)
       print("文件内容: \(String(describing: readString))")
      
  • 2.12.2、读取沙盒图片
    模仿SDWebImage: 加载图片前先去沙盒寻找,如果有就加载沙盒里的图片,没有的话就加载网络的图片

    • OC

      /** 读出图片 imageUrl: 图片的链接*/
      +(void)jKReadImageWithImageUrl:(NSString *)imageUrl withReadImage:(ReadImage)readImage{
      
         NSString *catchsImageStr = [imageUrl lastPathComponent];
         NSFileManager *fileManager = [NSFileManager defaultManager];
         NSString *filePath = [NSString stringWithFormat:@"%@/Library/Caches/JKImage/%@",NSHomeDirectory(),catchsImageStr];
      
         // fileExistsAtPath 判断一个文件或目录是否有效
         BOOL existed = [fileManager fileExistsAtPath:filePath];
      
         if ( !(existed == YES) ) {
            // 图片不存在沙盒里,检查文件夹是否存在 
            NSString *folderPath = [NSString stringWithFormat:@"%@/Library/Caches/JKImage",NSHomeDirectory()];
            BOOL isDir = NO;
            // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
            BOOL existedFolder = [fileManager fileExistsAtPath:folderPath isDirectory:&isDir];
            if ( !(isDir == YES && existedFolder == YES) ) {
      
                // 不存在的文件夹JKImage才会创建
                [fileManager createDirectoryAtPath:folderPath withIntermediateDirectories:YES attributes:nil error:nil];
            }
      
           // 文件夹存在就把图片缓存进去
           // 图片不存在
           NSData *data = [NSData dataWithContentsOfURL:[NSURL  URLWithString:imageUrl]];
           //转换为图片保存到以上的沙盒路径中
           UIImage * currentImage = [UIImage imageWithData:data];
           //其中参数0.5表示压缩比例,1表示不压缩,数值越小压缩比例越大
           [UIImageJPEGRepresentation(currentImage, 0.5) writeToFile:[NSString stringWithFormat:@"%@/%@",folderPath,catchsImageStr] atomically:YES];
           readImage(currentImage,YES);
      
         }else{
      
            // 图片在沙盒里直接取出
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            UIImage *image = [UIImage imageWithData:data];
            readImage(image,YES);
         }
       }
      
    • Swift

       let path = NSHomeDirectory() + "/Documents/2.png"
       let fileManagerReadImage = FileManager.default
       let exist = fileManagerReadImage.fileExists(atPath: path)
       // 不存在直接返回false
       if (!exist) {
         
           print("存在图片")
       }else{
         
          let readHandler =  FileHandle(forReadingAtPath: path)
          let data = (readHandler?.readDataToEndOfFile())!
          let image = UIImage(data: data)
        
          print("不存在图片")
       }
      
2.13、获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)
  • OC

    let docPath = NSHomeDirectory() + "/Documents/我的笔记.text"
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];
    
    if (fileAttributes != nil) {
       NSNumber *fileSize;
       NSString *fileOwner, *creationDate;
       NSDate *fileModDate;
       //NSString *NSFileCreationDate
       //文件大小
       if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
       
          NSLog(@"文件的大小= %qi\n", [fileSize unsignedLongLongValue]);
       }
       //文件创建日期
       if ((creationDate = [fileAttributes objectForKey:NSFileCreationDate])) {
       
          NSLog(@"文件创建的日期: %@\n", creationDate);
       }
       //文件所有者
       if ((fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName])) {
      
          NSLog(@"Owner: %@\n", fileOwner);
        }
        //文件修改日期
        if ((fileModDate = [fileAttributes objectForKey:NSFileModificationDate])) {
       
           NSLog(@"文件修改的日期: %@\n", fileModDate);
        }
    }else {
         NSLog(@"该文件不存在");
    }
    
  • Swift

    // 我的笔记.text文本是存在Documents下面的
    let path = NSHomeDirectory() + "/Documents/我的笔记.text"
    let managerGetFile = FileManager.default
    let attributes = try? managerGetFile.attributesOfItem(atPath: path) //结果为Dictionary类型
    print("创建时间:\(attributes[FileAttributeKey.creationDate]!)")
    print("修改时间:\(attributes[FileAttributeKey.modificationDate]!)")
    print("文件大小:\(attributes[FileAttributeKey.size]!)")
    
2.14、计算单个或多个文件夹的大小(清理数据常用)
  • OC

    /** 计算文件夹的大小 folderPath: 文件夹的大小*/
    -(NSString *)jKCalculateTheSizeOfTheFolderPath:(NSString *)folderPath{
    
       NSFileManager *fileManager = [NSFileManager defaultManager];
       BOOL isExist = [fileManager fileExistsAtPath:folderPath];
       if (isExist) {
    
           unsigned long long folderSize = 0;
           NSArray *childerFiles=[fileManager subpathsAtPath:folderPath];
    
           if (childerFiles.count != 0) {
       
                for (NSString *fileName in childerFiles) {
           
                   NSString *fileAbsolutePath=[folderPath stringByAppendingPathComponent:fileName];
                   folderSize +=[self jKCalculateTheSizeOfTheFilePath:fileAbsolutePath];
                }
           }else{
       
                folderSize = [self jKCalculateTheSizeOfTheFilePath:folderPath];
           }
    
          NSString *sizeString;
    
          if (folderSize >= 1024.0 * 1024.0) {
       
              sizeString = [NSString stringWithFormat:@"%.2fMB",folderSize / (1024.0 * 1024.0)];
          }else if (folderSize >= 1024.0){
       
              sizeString = [NSString stringWithFormat:@"%.fkb",folderSize / (1024.0)];
          }else{
       
              sizeString = [NSString stringWithFormat:@"%llub",folderSize];
          }
    
          // unsigned long long
          return sizeString;
    
       } else {
    
          NSLog(@"file is not exist");
          return @"0MB";
       }
    }
    
    /** 计算文件的大小*/
    -(unsigned long long)jKCalculateTheSizeOfTheFilePath:(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;
        }
    }
    
  • Swift

    /** 计算文件夹或者文件的大小 */
    class func getSize(folderPath: String)-> String
    {
      if folderPath.count == 0 {
          return "0MB" as String
      }
      let manager = FileManager.default
      if !manager.fileExists(atPath: folderPath){
          return "0MB" as String
      }
      var fileSize:Float = 0.0
      do {
            let files = try manager.contentsOfDirectory(atPath: folderPath)
          
            for file in files {
              
              let path = folderPath + "/\(file)"
              fileSize = fileSize + fileSizeAtPath(filePath: path)
              
            }
          }catch{
              
              fileSize = fileSize + fileSizeAtPath(filePath: folderPath)
      }
      
      print("大小==\(fileSize)")
      
      var resultSize = ""
      
      if fileSize >= 1024.0*1024.0{
          
          resultSize = NSString(format: "%.2fMB", fileSize/(1024.0 * 1024.0)) as String
    
      }else if fileSize >= 1024.0{
          
          resultSize = NSString(format: "%.fkb", fileSize/(1024.0 )) as String
          
      }else{
          
          resultSize = NSString(format: "%llub", fileSize) as String
      }
    
      return resultSize
    }
    
    /**  计算单个文件或文件夹的大小 */
    class func fileSizeAtPath(filePath:String) -> Float {
      
      let manager = FileManager.default
      var fileSize:Float = 0.0
      if manager.fileExists(atPath: filePath) {
          do {
              let attributes = try manager.attributesOfItem(atPath: filePath)
              
               if attributes.count != 0 {
                  
                  fileSize = attributes[FileAttributeKey.size]! as! Float
                }
             }catch{
          
             }
        }
      
       return fileSize;
    }
    
最后给大家提供上面封装的demo

JKSwiftFileOperationJKOCFilePathOperation

请给个喜欢,谢谢!我们的iOS开发交流QQ群:584599353

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容

  • iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...
    MacShare阅读 1,727评论 0 6
  • iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...
    Friez平板支撑阅读 4,524评论 0 1
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    绚雨蓝了个枫阅读 3,992评论 0 2
  • 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它一...
    tzhtodd阅读 1,240评论 0 2
  • 一、iOS中的沙盒机制 •iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭、安全的空间,叫做沙盒。它...
    舒城8中阅读 2,344评论 0 6