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

本文详细介绍iOS应用程序中的文件管理,包括沙盒概念、不同目录的作用、文件及文件夹的基本操作、文件属性获取、文件大小计算等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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

1
2
3
4
OC:                
NSString *filePath = NSHomeDirectory();
Swift:
let homePath = NSHomeDirectory()

2.1.2、Documents

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
11
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

1
2
3
4
5
6
7
8
9
10
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

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

1
2
3
4
5
6
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

1
2
3
4
5
6
7
8
9
10
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
// 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:

1
2
3
4
5
6
7
8
9
10
11
12
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

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

Swift:

1
2
3
4
5
6
7
8
9
  /** 对指定路径执行浅搜索,读取指定目录路径下的文件、子目录及符号链接的列表(只寻找一层)*/
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
+(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:

1
2
3
4
5
6
7
8
9
10
11
  func jkJudgeFileOrFolderExists(folderName: NSString) -> Bool
  {
     let filePath =  "\(folderName)"
     let exist = fileManager.fileExists(atPath: filePath)
     // 查看文件夹是否存在,如果存在就直接读取,不存在就直接反空
     if  (exist) {
        return  true
     } else {
       return  false
     }
  }

2.9、创建文件(如:动画乐园.text格式的文本文件)

创建文件(如:动画乐园.text格式的文本文件)

OC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  // 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.10、可以通过write(to:)方法,可以创建文件并将对象(文件,音频,图片,视频以及数组,字典)都可以写入文件

  • 简单对象:iOS中提供四种类型可以直接进行文件存取:NSString(字符串)、NSArray(数组)、NSDictionary(字典)、NSData(数据)(以上类型包括子类)

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

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

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

OC

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

Swift:

1
2
3
let path = NSHomeDirectory() +  "/Documents/动画乐园.text"
let info =  "动画乐园欢迎你"  as  String
try ! info.write(toFile: path, atomically:  true , encoding:  String .Encoding.utf8)
  • 2.10.2、把本地图片或者网络图片保存到上面“图片”的文件夹里面

filePath图片的路径是提前存在的(没有的话看上面的去创建文件夹)

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

OC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 本地图片的名字
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 *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:

1
2
3
4
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.10.3、把本数组写到文件里面(array.plist的文件是已经存在的基础上)

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

OC

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

Swift

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

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

OC

1
2
3
4
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

1
2
3
let filePath = NSHomeDirectory() +  "/Documents/dictionary.plist"
let dictionary = NSDictionary(dictionary: [ "name" : "JK" , "age" : "26" ])
dictionary.write(toFile: filePath, atomically:  true )

2.11、复制文件

复制文件

OC

1
2
3
4
  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

1
2
3
4
5
  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.12、移动文件或者文件夹

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

移动文件或者文件夹

OC

1
2
3
4
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

1
2
3
4
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.13、读取文件

  • 2.13.1、文件的类型为文本,如 我的笔记.text

OC

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

Swift

1
2
3
4
5
  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.13.2、读取沙盒图片

模仿SDWebImage: 加载图片前先去沙盒寻找,如果有就加载沙盒里的图片,没有的话就加载网络的图片

OC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/** 读出图片 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  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.14、获取文件属性(创建时间,修改时间,文件大小,文件类型等信息)

OC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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

1
2
3
4
5
6
7
// 我的笔记.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.15、计算单个或多个文件夹的大小(清理数据常用)

OC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/** 计算文件夹的大小 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/** 计算文件夹或者文件的大小 */
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;
}

转载于:https://www.cnblogs.com/ruixin-jia/p/8926316.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值