Rename file in Cocoa?

前端 未结 5 1305
再見小時候
再見小時候 2021-01-01 11:11

How would I rename a file, keeping the file in the same directory?

I have a string containing a full path to a file, and a string containing a the new filename (and

5条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 11:56

    For the icing on top, a category on NSFileManager:

    @implementation NSFileManager (FileManipulations)
    
    
    - (void)changeFileNamesInDirectory:(NSString *)directory changeBlock:(NSString * (^) (NSString *fileName))block
    {
        NSString *inputDirectory = directory;
    
        NSFileManager *fileManager = [NSFileManager new];
    
        NSArray *fileNames = [fileManager contentsOfDirectoryAtPath:inputDirectory error:nil];
        for (NSString *fileName in fileNames) {
    
            NSString *newFileName =  block(fileName);
    
            NSString *oldPath = [NSString stringWithFormat:@"%@/%@", inputDirectory, oldFileName];
            // move to temp path so case changes can happen
            NSString *tempPath = [NSString stringWithFormat:@"%@-tempName", oldPath];
            NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFileName];
    
            NSError *error = nil;
            [fileManager moveItemAtPath:oldPath toPath:tempPath error:&error];
            if (error) {
                NSLog(@"%@", [error localizedDescription]);
                return;
            }
            [fileManager moveItemAtPath:tempPath toPath:newPath error:&error];
            if (error) {
                NSLog(@"%@", [error localizedDescription]);
            }
        }
    }
    
    
    @end
    

提交回复
热议问题