1。实现方法:
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
e.g.
@property (nonatomic, strong) NSFileManager *fileManager;
/* 根据给定的路径创建文件夹 */- (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);
}
else {
NSLog(@"create folder:%@ in succeed",paramPath);
}
}
/* 在指定的路径下创建文件(在指定的文件夹里创建文件) */
- (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_%lu",(unsigned long)counter+1];
NSError *error = nil;
if ([fileContents writeToFile:path atomically:YES
encoding:NSUTF8StringEncoding error:&error] == NO){
NSLog(@"Failed to save file to %@. Error = %@", path, error);
}
}
NSLog(@"create files in folder succeed");
}
/* 遍历 */
- (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);
}
}
/* 删除 */
- (void) deleteFilesInFolder:(NSString *)paramPath{
NSError *error = nil;
NSArray *contents = [self.fileManager contentsOfDirectoryAtPath:paramPath error:&error];
if (error == nil){
for (NSString *fileName in contents){
/*filePath: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);
}
}
/* 删除文件夹*/
- (void) deleteFolder:(NSString *)paramPath{
NSError *error = nil;
if ([self.fileManager removeItemAtPath:paramPath error:&error] == NO){
NSLog(@"Failed to remove path %@. Error = %@", paramPath, error);
}else {
NSLog(@"succeed in remove path %@",paramPath);
}
-(void) actionFilesAndFolders{
self.fileManager = [[NSFileManager alloc] init];
NSString *txtFolder = [NSTemporaryDirectory() stringByAppendingPathComponent:@"txt"];
[self createFolder:txtFolder];
[self createFilesInFolder:txtFolder];
[self enumerateFilesInFolder:txtFolder];
[self deleteFilesInFolder:txtFolder];
[self enumerateFilesInFolder:txtFolder];
[self deleteFolder:txtFolder];
}
本文详细介绍了使用Objective-C语言进行文件操作的各项关键功能,包括创建文件夹、创建文件、遍历目录、删除文件及文件夹等。通过实例演示了如何在特定路径下创建文件夹,并在该文件夹中创建多个文件,同时提供了遍历目录获取文件信息的方法,以及删除文件和文件夹的操作。最后,展示了完整的文件操作流程,为开发者提供了一站式的文件管理解决方案。
1116

被折叠的 条评论
为什么被折叠?



