一、创建文件夹
// 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);
}
}