iOS 文件处理

NSString* imagePath = [[NSBundle mainBundle]pathForResource:@"menu_default" ofType:@"png"];

NSData* imageData = [NSData dataWithContentsOfFile:imagePath];

NSLog(@"imageData-%@",imageData);

//初始化文件管理器

NSFileManager* fileManager = [NSFileManager defaultManager];

//获取文件目录

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

NSString* path = [pathArr objectAtIndex:0];

NSString* path1 =[path stringByAppendingPathComponent:@"txt.txt"];

NSString* path2 =[path stringByAppendingPathComponent:@"test.txt"];

[imageData writeToFile:path1 atomically:YES];

//    [@"123" writeToFile:path2 atomically:YES encoding:NSUTF8StringEncoding error:nil];//写入文件

//移动文件---只能把文件移动到一个空的文件里

//    if ([fileManager moveItemAtPath:path1 toPath:path2 error:nil]) {

//

//        NSLog(@"移动文件");

//    }

//复制文件---只能把文件复制到一个空的文件里

//    if ([fileManager copyItemAtPath:path1 toPath:path2 error:nil]) {

//

//        NSLog(@"复制文件");

//    }

//删除文件

//    if ([fileManager removeItemAtPath:path2 error:nil]) {

//        NSLog(@"删除文件");

//    }

//写入文件

[fileManager createFileAtPath:path2 contents:[@"123" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

//读取文件

NSData* data = [fileManager contentsAtPath:path2];

NSString* str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

NSLog(@"str----%@",str);

//    if ([fileManager isReadableFileAtPath:path2]) {

//

//        NSLog(@"是否可读");

//    }

//

//

//    if ([fileManager isWritableFileAtPath:path1]) {

//        NSLog(@"是否可写");

//

//    }

//    if ([fileManager isExecutableFileAtPath:path1]) {

//        NSLog(@"是否可执行");

//    }

//    //比较两个文件的内容

//    if ([fileManager contentsEqualAtPath:path1 andPath:path2]) {

//        NSLog(@"成功");

//    }else{

//        NSLog(@"失败");

//

//    }

//检查文件是否存在

//    if ([fileManager fileExistsAtPath:path]) {

//

//        UIAlertController* alertC = [UIAlertController alertControllerWithTitle:@"系统公告" message:@"目录存在" preferredStyle:UIAlertControllerStyleAlert];

//        UIAlertAction* alertAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

//

//        }];

//        [alertC addAction:alertAction];

//

//        AppDelegate* delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;

//        [delegate.window.rootViewController presentViewController:alertC animated:YES completion:nil];

//    }

你可能感兴趣的:(iOS 文件处理)