沙盒文件以及文件夹操作

来源:互联网 发布:知乎产品分析报告 编辑:程序博客网 时间:2024/04/30 09:58
- (void)viewDidLoad {    [super viewDidLoad];    NSLog(@"%@",NSHomeDirectory());    }- (IBAction)createFileClick:(UIButton *)sender {        //NSFileManager文件管理器,单例类    NSFileManager *manager = [NSFileManager defaultManager];    NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"];        //createFileAtPath创建一个文件,第一个参数是创建的路径,第二个参数是文件内容,第三个参数是文件属性。    if ([manager createFileAtPath:path contents:nil attributes:nil]) {        NSLog(@"创建成功");    }else{        NSLog(@"创建失败");    }}- (IBAction)deleteFileClick:(UIButton *)sender {    NSError *error = nil;        //removeItemAtPath删除一个文件或文件夹,第一个参数是要删除的文件的路径,第二个参数是如果删除失败,失败的原因。    if (![[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"] error:&error]) {        NSLog(@"%@",error);    }}- (IBAction)createDirectoryClick:(UIButton *)sender {    NSString *dirPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/123/456"];        //createDirectoryAtPath创建一个文件夹,第一个参数是创建的文件夹的路径,第二个参数是是否自动创建路径中不存在的文件夹。    [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];}- (IBAction)copyFileClick:(UIButton *)sender {        //赋值一个文件,第一个参数是要复制的文件的路径,第二个参数是复制目标路径(必须添加新的文件名)。    [[NSFileManager defaultManager] copyItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/file1.txt"] toPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/123/456/copyedFile.txt"] error:nil];}- (IBAction)moveFileClick:(UIButton *)sender {    [[NSFileManager defaultManager] moveItemAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/123/456/copyedFile.txt"] toPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/123/copyedFile.txt"] error:nil];}- (IBAction)isFileExistClick:(UIButton *)sender {        //fileExistsAtPath判断一个文件或文件夹是否存在,isDirectory路径目标是文件还是文件夹。    BOOL isDirectory;    if ([[NSFileManager defaultManager] fileExistsAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents/456"] isDirectory:&isDirectory]) {        NSLog(@"存在");        if (isDirectory) {            NSLog(@"是文件夹");        }else{            NSLog(@"是文件");        }    }else{        NSLog(@"不存在");    }}

7 0