沙盒文件以及文件夹操作

- (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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值