iOS文件系统(操作文件)

1.操作文件(使用NSFileManager进行如创建,复制,删除等操作)

通过一个实例代码记录主要操作方法,下面的方法描述了备份某文件的操作由于文件的操作一般都是耗时操作所以最好放在子线程下进行。

- (void)backUpMyApplicationData{ 

 NSString *bundId = [[NSBundle mainBundle] bundleIdentifier]; 

 NSFileManager *manager = [NSFileManager defaultManager]; 

 NSArray *filesArr = [manager URLsForDirectory:NSApplicationSupportDirectory inDomains:NSUserDomainMask] ; 

 NSURL *dataDir;

 if (filesArr.count>0) {

 NSURL* supDir = [filesArr objectAtIndex:0]; 

 dataDir = [[supDir URLByAppendingPathComponent:bundId] URLByAppendingPathComponent:@"Data"]; 

 // Copy the data to ~/Library/Application Support//Data.backup

        NSURL *backupDir = [dataDir URLByAppendingPathExtension:@"backup"];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            // It's good habit to alloc/init the file manager for move/copy operations,

            // just in case you decide to add a delegate later.

            NSError *error;

            NSFileManager *manager = [[NSFileManager alloc] init];

        //通过返回布尔值判断操作是否成功

            if (![manager copyItemAtURL:dataDir toURL:backupDir error:&error]) {

                NSLog(@"copy error==%@",error.localizedDescription);

                // If an error occurs, it's probably because a previous backup directory

                // already exists.  Delete the old directory and try again.

                if ([manager removeItemAtURL:backupDir error:&error]) {

                    //try agian

                    if (![manager copyItemAtURL:dataDir toURL:backupDir error:&error]) {

                        NSLog(@"backup fail==%@",error.localizedDescription);

                    }

                    else{

                        NSLog(@"back up success");

                    }

                }

                else{

                  NSLog(@"remove error==%@",error.localizedDescription);

                }

            }else{

                NSLog(@"back up success");

            }


        });

    }

}



2.读写文件

1.通过NSFileHandle

- (void)WriteHandle:(NSURL*)url{

    NSString *str = @"assume you are a genius";

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

    NSError *error;

    NSFileHandle *handle = [NSFileHandle fileHandleForWritingToURL:url error:&error];

    if (error) {

        NSLog(@"handl write error==%@",error.localizedDescription);

        return;

    }

    [handle writeData:data];

    [handle closeFile];

}

- (void)readHanle:(NSURL*)url{

    NSError*error;

    NSFileHandle *handle = [NSFileHandle fileHandleForReadingFromURL:url error:&error];

    if (error) {

        NSLog(@"handl read error==%@",error.localizedDescription);

    }

    NSData *data=  [handle readDataToEndOfFile];

    NSLog(@"read data==%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

    [handle closeFile];

}

//NSData 的write 和dataWithContentsOfURL进行读写

- (void)dataDirct{

    NSError*error;

    NSURL *url = [[[[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask] firstObject]URLByAppendingPathComponent:@"myggod"];

    NSString *str =@"congratulation you are a sb";

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];


    [data writeToURL:url options:NSDataWritingFileProtectionMask error:&error];

    if (error) {

        NSLog(@"data write error==%@",error.localizedDescription);

    }


//    [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:nil];

    NSData*readata = [NSData dataWithContentsOfURL:url];

    NSLog(@"read data===%@",[[NSString alloc]initWithData:readata encoding:NSUTF8StringEncoding]);

}

 ps:以上操作最好在非主线程中操作。

你可能感兴趣的:(iOS文件系统(操作文件))