美文网首页
数据持久化---文件操作相关方法

数据持久化---文件操作相关方法

作者: 雨_田 | 来源:发表于2019-03-03 01:18 被阅读0次

//获取应用程序路径

+ (NSString *)getApplicationPath {
    return NSHomeDirectory();
}

//获取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];
}

//获取tmp路径

+ (NSString *)getTmpPath {
    return NSTemporaryDirectory();
}

//获取SystemData路径

+ (NSString *)getSystemDataPath {
    //stringByAppendingString是字符串拼接,拼接路径时要在名称前加“/”
    //stringByAppendingPathComponent是路径拼接,会在字符串前自动添加“/”,成为完整路径
    NSString *path = [NSHomeDirectory() stringByAppendingString:@"/SystemData"];
    //NSString *path = [path stringByAppendingPathComponent:@"SystemData"];
    return path;
}

//获取Preferences路径

+ (NSString *)getPreferencesPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSPreferencePanesDirectory, NSUserDomainMask, YES);
    return [filePaths objectAtIndex:0];
}

//获取Caches路径

+ (NSString *)getCachesPath {
    NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [filePaths objectAtIndex:0];
}

//根据文件路径获取文件名称

+ (NSString *)getFileNameWithPath:(NSString *)path {
    NSArray *array= [path componentsSeparatedByString:@"/"];
    if (array.count == 0) {
        return path;
    }
    return [array objectAtIndex:array.count-1];
}

//根据文件名获取资源文件路径

+ (NSString *)getResourcesFileWithName:(NSString *)name {
    return [[NSBundle mainBundle] pathForResource:name ofType:nil];
}

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

+ (BOOL)fileIsExistOfPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:path];
}

//从某个路径中移除文件

+ (BOOL)removeFileOfPath:(NSString *)path {
    BOOL flag = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
      BOOL isExist = [fileManager fileExistsAtPath:path];
    if (isExist) {
        NSError *error;
        BOOL isRemoveSuccess = [fileManager removeItemAtPath:path error:&error];
        if (!isRemoveSuccess) {
            flag = NO;
        }
    }
    return flag;
}

//从URL路径中移除文件

+ (BOOL)removeFileOfURL:(NSURL *)fileURL {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:fileURL.path];
    if (isExist) {
        NSError *error;
        isSuccess = [fileManager removeItemAtURL:fileURL error:&error];
        if (!isSuccess) {
            NSLog(@"removeFileOfURL Failed. errorInfo:%@",error);
        }
    }
    return isSuccess;
}

//创建创建文件夹/目录

+ (BOOL)creatFileDirectoryWithPath:(NSString *)path {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:path];
    if (!isExist) {
        NSError *error;
        isSuccess = [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
        if (!isSuccess) {
            NSLog(@"creatFileDirectoryWithPath Failed. errorInfo:%@",error);
        }
    }
    return isSuccess;
}

//创建待写入的空文件:如test.xlArchiver

+ (BOOL)creatFileWithPath:(NSString *)path {
    BOOL isSuccess = YES;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:path];
    if (isExist) {
        return YES;
    }
    NSError *error;
    //stringByDeletingLastPathComponent:删除最后一个路径节点
    NSString *dirPath = [path stringByDeletingLastPathComponent];
    isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
    if (error) {
        NSLog(@"creatFileWithPath Failed. errorInfo:%@",error);
    }
    if (!isSuccess) {
        return isSuccess;
    }
    isSuccess = [fileManager createFileAtPath:path contents:nil attributes:nil];
    return isSuccess;
}

//保存文件

+ (BOOL)saveFile:(NSString *)filePath withData:(NSData *)data {
    BOOL isSuccess = YES;
    isSuccess = [self creatFileWithPath:filePath];
    if (isSuccess) {
        isSuccess = [data writeToFile:filePath atomically:YES];
        if (!isSuccess) {
            NSLog(@"%s Failed",__FUNCTION__);
        }
    } else {
        NSLog(@"%s Failed",__FUNCTION__);
    }
    return isSuccess;
}

//追加写文件

+ (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 *)getFileDataWithPath:(NSString *)path {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    NSData *fileData = [handle readDataToEndOfFile];
   [handle closeFile];
   return fileData;
}

//读取文件

+ (NSData *)getFileDataWithPath:(NSString *)path startIndex:(long long)startIndex length:(NSInteger)length {
    NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];
    [handle seekToFileOffset:startIndex];
    NSData *data = [handle readDataOfLength:length];
    [handle closeFile];
    return data;
}

//移动文件

+ (BOOL)moveFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    BOOL isSuccess = YES;
    NSError *error;
    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]) {
        isSuccess = [fileManager moveItemAtPath:fromPath toPath:toPath error:&error];
        if (!isSuccess) {
            NSLog(@"moveFileFromPath:toPath: Failed. errorInfo:%@", error);
        }
        return isSuccess;
    } else {
        return NO;
    }
}

//拷贝文件

+ (BOOL)copyFileFromPath:(NSString *)fromPath toPath:(NSString *)toPath {
    BOOL isSuccess = YES;
    NSError *error;
    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]) {
        isSuccess = [fileManager copyItemAtPath:fromPath toPath:toPath error:&error];
        if (!isSuccess) {
             NSLog(@"copyFileFromPath:toPath: Failed. errorInfo:%@", error);
        }
        return isSuccess;
    } else {
        return NO;
    }
}

//重命名文件或目录

//判断对象为空
UIKIT_STATIC_INLINE BOOL StrIsEmpty(id aItem) {
    return aItem == nil
    || ([aItem isKindOfClass:[NSNull class]])
    || (([aItem respondsToSelector:@selector(length)])
    && ([aItem length] == 0))
    || (([aItem respondsToSelector:@selector(count)])
    && ([aItem count] == 0));
}
+ (BOOL)reNameFileWithPath:(NSString *)path toName:(NSString *)toName {
    BOOL isSuccess = YES;
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //获取文件名: 如 视频.MP4
    NSString *lastPathComponent = [path lastPathComponent];
    //获取后缀:MP4
    NSString *pathExtension = [path pathExtension];
    //用传过来的路径创建新路径 首先去除文件名
    NSString *aimPath = [path stringByReplacingOccurrencesOfString:lastPathComponent withString:@""];
    //对文件重命名
    NSString *moveToPath;
    if (StrIsEmpty(pathExtension)) {//没有后缀
        moveToPath = [NSString stringWithFormat:@"%@%@",aimPath, toName];
    } else {
        moveToPath = [NSString stringWithFormat:@"%@%@.%@",aimPath, toName ,pathExtension];
    }
    //通过移动该文件对文件重命名
    isSuccess = [fileManager moveItemAtPath:path toPath:moveToPath error:&error];
    if (!isSuccess){
        NSLog(@"reNameFileWithPath:toName: Failed, errorInfo:%@",error);
    } else {
        NSLog(@"reName success");
    }
    return isSuccess;
}

//获取文件夹下文件列表---该路径下所有目录

+ (NSArray *)getFileListInFolderWithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileListInFolderWithPath Failed, errorInfo:%@",error);
    }
    return fileList;
}

//获取文件目录下所有文件

+ (NSArray *)getAllFloderWithPath:(NSString *)path {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *fileAndFloderArr = [self getFileListInFolderWithPath:path];
    NSMutableArray *dirArray = [NSMutableArray new];
    BOOL isDir = NO;
    //在上面那段程序中获得的fileList中列出文件夹名
    for (NSString * file in fileAndFloderArr){
        NSString *paths = [path stringByAppendingPathComponent:file];
        [fileManager fileExistsAtPath:paths isDirectory:(&isDir)];
        if (isDir) {
            [dirArray addObject:file];
        }
        isDir = NO;
    }
    return dirArray;
}

//获取文件大小

+ (int64_t)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];
    }
    return fileLength;
    */
    NSDirectoryEnumerator *pathEnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
    NSString *eName;
    int64_t fileSize = 0;
    while (eName = [pathEnum nextObject]){
        //NSLog(@"eName:%@",eName);
        NSDictionary *currentdict = [pathEnum fileAttributes];
        NSString     *filesize = [NSString stringWithFormat:@"%@",[currentdict objectForKey:NSFileSize]];
        NSString     *filetype = [currentdict objectForKey:NSFileType];
        if([filetype isEqualToString:NSFileTypeDirectory]) {
            continue;
        }
        fileSize = fileSize + [filesize longLongValue];
    }
    return fileSize;

}

//获取文件创建时间

+ (NSString *)getFileCreatDateWithPath:(NSString *)path {
    NSError  *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileCreatDateWithPath Failed, errorInfo:%@",error);
    }
    NSString *date = [fileAttributes objectForKey:NSFileCreationDate];
    return date;
}

//获取文件更改时间

+ (NSString *)getFileChangeDateWithPath:(NSString *)path {
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileChangeDateWithPath Failed, errorInfo:%@",error);
    }
    NSString *date = [fileAttributes objectForKey:NSFileModificationDate];
    return date;
}

//获取文件所有者

+ (NSString *)getFileOwnerWithPath:(NSString *)path {
    NSError *error;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:&error];
    if (error) {
        NSLog(@"getFileOwnerWithPath Failed, errorInfo:%@",error);
    }
    NSString *fileOwner = [fileAttributes objectForKey:NSFileOwnerAccountName];
    return fileOwner;
}

相关文章

  • 数据持久化---文件操作相关方法

    //获取应用程序路径 //获取Document路径 //获取Library路径 //获取tmp路径 //获取Sys...

  • Lesson 0-3 Objective-C basic

    15. 数据持久化 数据持久化方式: plist:属性列表plist 文件的常见操作 NSUserDefaults...

  • 文件与流-1

    文件与流 持久化操作:(文件里、数据库里)Java.io 文件分隔符 目录操作 文件操作

  • 19-01-09recode

    day12总结文件操作,数据持久化 1.打开文件 -> 操作文件 -> 关闭文件文件对象 = open(...

  • day17 文件操作

    1. 文件操作 os库提供了很多和文件管理操作 1.1 数据本地化和数据持久化 通过文件将数据存到硬盘中数据库文件...

  • iOS开发-数据持久化之plist文件

    摘要 通过对plist文件的操作对iOS开发中一些数据进行持久化保存。 iOS数据持久化之一——plist文件 i...

  • python的文件操作

    1.数据的存储 2.文件操作 -操作文件内容 文件路径 2.2操作文件 数据的持久化 文件域 3.容器字符串...

  • python——文件读写与异常处理

    文件 在实际开发中,常常需要对程序中的数据进行持久化操作,而实现数据持久化最直接简单的方式就是将数据保存到文件中。...

  • MyBatis必知必会

    流程 创建持久化类(POJO类) 编写持久化操作的Mapper文件,其中定义SQL语句 创建配置文件:连接哪种数据...

  • 005-文件

    文件操作介绍 文件的概念 文件的作用数据持久化 文件的打开与关闭 生活实例(文件的操作)打开work文档修改数据保...

网友评论

      本文标题:数据持久化---文件操作相关方法

      本文链接:https://www.haomeiwen.com/subject/tbruuqtx.html