文件和文件夹的管理

一、创建文件夹

// Create a folder at a given path
- (void)createFolder:(NSString *)paramPath {
    NSError *error = nil;
    if ([self.fileManager createDirectoryAtPath:paramPath withIntermediateDirectories:YES attributes:nil error:&error] == NO) {
        NSLog(@"Failed to create folder %@. Error = %@", paramPath, error);
    }
}

二、在文件夹中创建文件

// Create txt files in the given folder
- (void)createFilesInFolder:(NSString *)paramPath {
    for (NSUInteger counter =  0; counter < 5; counter++) {
        NSString *fileName = [NSString stringWithFormat:@"%lu.txt", (unsigned long)counter+1];
        NSString *path = [paramPath stringByAppendingPathComponent:fileName];
        NSString *fileContents = [NSString stringWithFormat:@"Some text"];
        NSError *error = nil;
        if ([fileContents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error] == NO) {
            NSLog(@"Failed to save file to %@. Error = %@", path, error);
        }
    }
}

三、遍历文件夹中的文件

// Enumerates all files/folders at a given path
- (void)enumerateFilesInFolder:(NSString *)paramPath {
    NSError *error = nil;
    NSArray *contents = [self.fileManager contentsOfDirectoryAtPath:paramPath error:&error];;
    if ([contents count] > 0 && error ==nil) {
        NSLog(@"Contents of path %@ = \n%@", paramPath, contents);
    } else if ([contents count] == 0 && error == nil) {
        NSLog(@"Contents of path %@ is empty!", paramPath);
    } else {
        NSLog(@"Failed to enumerate path %@. Error = %@", paramPath, error);
    }
}

四、删除文件夹下的所有文件

// Deletes all files/folders in a given path
- (void)deleteFilesInFolder:(NSString *)paramPath {
    NSError *error = nil;
    NSArray *contents = [self.fileManager contentsOfDirectoryAtPath:paramPath error:&error];
    if (error == nil) {
        error = nil;
        for (NSString *fileName in contents) {
            // We have the filename, to delete it, we have to have the full path
            NSString *filePath = [paramPath stringByAppendingPathComponent:fileName];
            if ([self.fileManager removeItemAtPath:filePath error:&error] == NO) {
                NSLog(@"Failed to remove item at path %@. Error = %@", fileName, error);
            } else {
                NSLog(@"Failed to enumerate path %@. Error = %@", paramPath, error);
            }
        }
    }
}

五、删除文件夹

// Deletes a folder with a given path
- (void)deleteFolder:(NSString *)paramPath {
    NSError *error = nil;
    if ([self.fileManager removeItemAtPath:paramPath error:&error] == NO) {
        NSLog(@"Failed to remove path %@. Error = %@", paramPath, error);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值