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

简介: Swift&OC 文件夹和文件的详细操作(下)
  • 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图片的路径是提前存在的(没有的话看上面的去创建文件夹)


image.png


  • 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的文件是已经存在的基础上)

image.png

  • 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的文件是已经存在的基础上)


image.png

  • 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、复制文件

image.png


  • 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要提前建好,创建方式看上面


image.png

  • 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

目录
相关文章
|
3月前
|
Swift Perl
OC和swift混合工程更新库时报:target has transitive dependencies that include statically linked binaries
OC和swift混合工程更新库时报:target has transitive dependencies that include statically linked binaries
42 0
|
10月前
|
API Swift iOS开发
45 Swift和OC的混编
Swift和OC的混编
106 0
|
11月前
|
Swift iOS开发
iOS OC混编Swift 后者无法走断点
iOS OC混编Swift 后者无法走断点
69 0
|
Swift iOS开发
IOS使用Swift加载Xib文件
IOS使用Swift加载Xib文件
292 0
|
Swift
《OpenStack Swift 海量小文件优化之路》电子版地址
OpenStack Swift 海量小文件优化之路
70 0
《OpenStack Swift 海量小文件优化之路》电子版地址
|
Swift iOS开发
Swift - 与OC混编时如何创建桥接头文件
Swift - 与OC混编时如何创建桥接头文件
417 0
Swift - 与OC混编时如何创建桥接头文件
|
Swift
Swift和OC控制器互相跳转
Swift和OC控制器互相跳转
304 0
|
Swift
Swift - pods中导入的Object-C文件在桥接文件中写入找不到的问题
Swift - pods中导入的Object-C文件在桥接文件中写入找不到的问题
129 0
|
Swift
OC 和 swift 创建单例方法
OC 和 swift 创建单例方法
310 0
|
29天前
|
Unix 调度 Swift
苹果iOS新手开发之Swift 中获取时间戳有哪些方式?
在Swift中获取时间戳有四种常见方式:1) 使用`Date`对象获取秒级或毫秒级时间戳;2) 通过`CFAbsoluteTimeGetCurrent`获取Core Foundation的秒数,需转换为Unix时间戳;3) 使用`DispatchTime.now()`获取纳秒级精度的调度时间点;4) `ProcessInfo`提供设备启动后的秒数,不表示绝对时间。不同方法适用于不同的精度和场景需求。
30 3