iOS NSFileManager

简介

由于项目需要,整理了一份文件处理的方法。

下面是一些常用的方法:

获取Document路径

+ (NSString *)getDocumentPath
{

 NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

 return [filePaths objectAtIndex:0];

}

获取Library路径

+ (NSString *)getLibraryPath
{
  
  NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);

  return [filePaths objectAtIndex:0];
}

获取应用程序路径

+ (NSString *)getApplicationPath
{

  return NSHomeDirectory();

}

获取Cache路径

+ (NSString *)getCachePath
{

  NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

  return [filePaths objectAtIndex:0];

}

获取Temp路径

+ (NSString *)getTempPath
{

  return NSTemporaryDirectory();

}

判断文件是否存在于某个路径中

+ (BOOL)fileIsExistOfPath:(NSString *)filePath
{

  BOOL flag = NO;

  NSFileManager *fileManager = [NSFileManager defaultManager];

  if ([fileManager fileExistsAtPath:filePath]) {
  
    flag = YES;

  } else {
  
    flag = NO;

  }

  return flag;
 
}

从某个路径中移除文件

+ (BOOL)removeFileOfPath:(NSString *)filePath
{

  BOOL flag = YES;

  NSFileManager *fileManage = [NSFileManager defaultManager];

  if ([fileManage fileExistsAtPath:filePath]) {
    if (![fileManage removeItemAtPath:filePath error:nil]) {
        flag = NO;
    }
  }

  return flag;

}

从URL路径中移除文件

- (BOOL)removeFileOfURL:(NSURL *)fileURL
{

  BOOL flag = YES;

  NSFileManager *fileManage = [NSFileManager defaultManager];

  if ([fileManage fileExistsAtPath:fileURL.path]) {
      if (![fileManage removeItemAtURL:fileURL error:nil]) {
          flag = NO;
      }
  }

   return flag;
}

创建文件路径

+(BOOL)creatDirectoryWithPath:(NSString *)dirPath
{

  BOOL ret = YES;

  BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:dirPath];

  if (!isExist) {
  
    NSError *error;
  
    BOOL isSuccess = [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
  
    if (!isSuccess) {
  
        ret = NO;
  
        NSLog(@"creat Directory Failed. errorInfo:%@",error);
  
    }

  }

  return ret;

}

创建文件

+ (BOOL)creatFileWithPath:(NSString *)filePath
{

    BOOL isSuccess = YES;

  NSFileManager *fileManager = [NSFileManager defaultManager];

  BOOL temp = [fileManager fileExistsAtPath:filePath];

  if (temp) {
  
    return YES;

  }

  NSError *error;

  //stringByDeletingLastPathComponent:删除最后一个路径节点

  NSString *dirPath = [filePath stringByDeletingLastPathComponent];

  isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];

  if (error) {
  
    NSLog(@"creat File Failed. errorInfo:%@",error);

  }

  if (!isSuccess) {
  
    return isSuccess;

  }

  isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];

   return isSuccess;

}

保存文件

+ (BOOL)saveFile:(NSString *)filePath withData:(NSData *)data
{

  BOOL ret = YES;

  ret = [self creatFileWithPath:filePath];

  if (ret) {
  
    ret = [data writeToFile:filePath atomically:YES];
  
    if (!ret) {
  
        NSLog(@"%s Failed",__FUNCTION__);
  
    }

  } else {
  
    NSLog(@"%s Failed",__FUNCTION__);

  }

  return ret;

}

追加写文件

+ (BOOL)appendData:(NSData *)data withPath:(NSString *)path
{

  BOOL result = [self creatFileWithPath:path];

  if (result) {
  
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
  
    [handle seekToEndOfFile];
  
    [handle writeData:data];
  
    [handle synchronizeFile];
  
    [handle closeFile];
  
    return YES;

  } else {
  
    NSLog(@"%s Failed",__FUNCTION__);
  
    return NO;

  }

}

获取文件

+ (NSData *)getFileData:(NSString *)filePath
{

  NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];

   NSData *fileData = [handle readDataToEndOfFile];

  [handle closeFile];

  return fileData;

}

读取文件

+ (NSData *)getFileData:(NSString *)filePath startIndex:(long long)startIndex length:(NSInteger)length
{

  NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:filePath];

 [handle seekToFileOffset:startIndex];

  NSData *data = [handle readDataOfLength:length];

 [handle closeFile];

 return data;

}

移动文件

+ (BOOL)moveFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath
{

  NSFileManager *fileManager = [NSFileManager defaultManager];

  if (![fileManager fileExistsAtPath:fromPath]) {
  
    NSLog(@"Error: fromPath Not Exist");
  
    return NO;

  }

  if (![fileManager fileExistsAtPath:toPath]) {
  
    NSLog(@"Error: toPath Not Exist");
  
    return NO;
 
  }

   NSString *headerComponent = [toPath stringByDeletingLastPathComponent];

  if ([self creatFileWithPath:headerComponent]) {
  
    return [fileManager moveItemAtPath:fromPath toPath:toPath error:nil];

  } else {
  
    return NO;

  }

}

拷贝文件

+(BOOL)copyFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath
{

  NSFileManager *fileManager = [NSFileManager defaultManager];

  if (![fileManager fileExistsAtPath:fromPath]) {
  
    NSLog(@"Error: fromPath Not Exist");
  
    return NO;

  }

  if (![fileManager fileExistsAtPath:toPath]) {
  
    NSLog(@"Error: toPath Not Exist");
  
    return NO;

  }

  NSString *headerComponent = [toPath stringByDeletingLastPathComponent];

  if ([self creatFileWithPath:headerComponent]) {
  
    return [fileManager copyItemAtPath:fromPath toPath:toPath error:nil];

  } else {
  
    return NO;

  }

}

获取文件夹下文件列表

+ (NSArray *)getFileListInFolderWithPath:(NSString *)path
{

  NSFileManager *fileManager = [NSFileManager defaultManager];

  NSError *error;

   NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];

  if (error) {
  
    NSLog(@"getFileListInFolderWithPathFailed, errorInfo:%@",error);

  }

  return fileList;

}

获取文件大小

+ (long long)getFileSizeWithPath:(NSString *)path
{
      
  unsigned long long fileLength = 0;

  NSNumber *fileSize;

  NSFileManager *fileManager = [NSFileManager defaultManager];

  NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];

  if ((fileSize = [fileAttributes objectForKey:NSFileSize])) {
  
    fileLength = [fileSize unsignedLongLongValue]; //单位是 B

  }

  return fileLength / 1000; 换算为K

}

获取文件创建时间

+ (NSString *)getFileCreatDateWithPath:(NSString *)path
{

  NSString *date = nil;

  NSFileManager *fileManager = [NSFileManager defaultManager];

  NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];

  date = [fileAttributes objectForKey:NSFileCreationDate];

  return date;

}

获取文件所有者

+ (NSString *)getFileOwnerWithPath:(NSString *)path
{

  NSString *fileOwner = nil;

  NSFileManager *fileManager = [NSFileManager defaultManager];

  NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];

  fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName];

  return fileOwner;

}

获取文件更改日期

+ (NSString *)getFileChangeDateWithPath:(NSString *)path
{

  NSString *date = nil;

  NSFileManager *fileManager = [NSFileManager defaultManager];

  NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];

  date = [fileAttributes objectForKey:NSFileModificationDate];

  return date;

}

获取文件的信息(包含了上面文件大小)

+(NSDictionary*)getFileInfo:(NSString*)path{

   NSError *error;

  NSDictionary *reslut =  [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];

  if (error) {
  
    NSLog(@"getFileInfo Failed:%@",[error localizedDescription]);

  }

  return reslut;

}

创建文件目录

- (void)createDir {

  NSString * docsdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

  NSString *dataFilePath = [docsdir stringByAppendingPathComponent:@"archiver"]; // 在Document目录下创建 "archiver" 文件夹

  NSFileManager *fileManager = [NSFileManager defaultManager];

  BOOL isDir = NO;

  // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
  BOOL existed = [fileManager fileExistsAtPath:dataFilePath isDirectory:&isDir];

  if (!(isDir && existed)) {
    // 在Document目录下创建一个archiver目录
    [fileManager createDirectoryAtPath:dataFilePath withIntermediateDirectories:YES attributes:nil error:nil];
  }

  // 在archiver下写入文件
  NSString *path = [dataFilePath stringByAppendingPathComponent:@"my.txt"];
  
  NSString *text = @"It's a beautiful day.";

  BOOL writeSuccess = [text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];

  if (writeSuccess) {
      NSLog(@"写入成功");
  }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言:iOS的沙盒机制,应用只能访问自己应用目录下的文件。iOS不像android,没有SD卡概念,不能直接访问图...
    ChinaSwift阅读 6,593评论 1 12
  • NSFileManager是一个单例类,也是一个文件管理器。可以通过NSFileManager创建文件夹、创建文件...
    _YZG_阅读 11,433评论 0 6
  • 使用NSFileManager 文件系统接口 允许访问文件夹内容 创建,重命名,删除文件,修改文件和文件属性,以及...
    扬扬扬阅读 13,037评论 2 11
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,105评论 2 89
  • 也不是所有人都适合做减法的,像我这种本来就没什么强烈意志的,减着减着就没了吧? 文中的“硬通货”/...
    不覺晓阅读 1,813评论 0 0