码迷,mamicode.com
首页 > 移动开发 > 详细

iOS 关于文件操作 NSFileManager

时间:2018-02-01 17:17:53      阅读:356      评论:0      收藏:0      [点我收藏+]

标签:pos   one   turn   nts   attribute   rip   amp   tom   file   

  • 创建文件夹
    + (BOOL)creatDir:(NSString *)path {
        if (path.length==0) {
            return NO;
        }
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL isSuccess = YES;
        BOOL isExist = [fileManager fileExistsAtPath:path];
        if (isExist==NO) {
            NSError *error;
            if (![fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
                isSuccess = NO;
                NSLog(@"creat Directory Failed:%@",[error localizedDescription]);
            }
        }
        return isSuccess;
    }
    

      

  • 创建文件
    + (BOOL)creatFile:(NSString*)filePath {
        if (filePath.length==0) {
            return NO;
        }
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:filePath]) {
            return YES;
        }
        NSError *error;
        NSString *dirPath = [filePath stringByDeletingLastPathComponent];
        BOOL isSuccess = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:&error];
        if (error) {
            NSLog(@"creat File Failed:%@",[error localizedDescription]);
        }
        if (!isSuccess) {
            return isSuccess;
        }
        isSuccess = [fileManager createFileAtPath:filePath contents:nil attributes:nil];
        return isSuccess;
    }
    

      

  • 写入文件
    + (BOOL)writeToFile:(NSString*)filePath contents:(NSData *)data {
        if (filePath.length==0) {
            return NO;
        }
        BOOL result = [self creatFile:filePath];
        if (result) {
            if ([data writeToFile:filePath atomically:YES]) {
                NSLog(@"write Success");
            }else{
                NSLog(@"write Failed");
            }
        }
        else{
            NSLog(@"write Failed");
        }
        return result;
    }
    

      

  • 追加数据
    + (BOOL)appendData:(NSData*)data withPath:(NSString *)filePath {
        if (filePath.length==0) {
            return NO;
        }
        BOOL result = [self creatFile:filePath];
        if (result) {
            NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
            [handle seekToEndOfFile];
            [handle writeData:data];
            [handle synchronizeFile];
            [handle closeFile];
        }
        else{
            NSLog(@"appendData Failed");
        }
        return result;
    }

  

 

iOS 关于文件操作 NSFileManager

标签:pos   one   turn   nts   attribute   rip   amp   tom   file   

原文地址:https://www.cnblogs.com/gwca/p/8399146.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!