Question

Comment puis-je renommer un fichier, en gardant le fichier dans le même répertoire?

J'ai une chaîne contenant un chemin d'accès complet à un fichier, et une chaîne contenant un nouveau nom de fichier (et pas de chemin), par exemple:

NSString *old_filepath = @"/Volumes/blah/myfilewithrubbishname.avi";
NSString *new_filename = @"My Correctly Named File.avi";

Je sais de NSFileManager movePath: toPath: gestionnaire: méthode , mais je ne peux pas entraîner comment construire le chemin du nouveau fichier ..

En fait, je suis à la recherche de l'équivalent au code Python suivant:

>>> import os
>>> old_filepath = "/Volumes/blah/myfilewithrubbishname.avi"
>>> new_filename = "My Correctly Named File.avi"
>>> dirname = os.path.split(old_filepath)[0]
>>> new_filepath = os.path.join(dirname, new_filename)
>>> print new_filepath
/Volumes/blah/My Correctly Named File.avi
>>> os.rename(old_filepath, new_filepath)
Était-ce utile?

La solution

NSFileManager et NSWorkspace ont tous les deux méthodes de manipulation de fichiers, mais le NSFileManager est de - (BOOL)movePath:(NSString *)source toPath:(NSString *)destination handler:(id)handler probablement votre meilleur pari. Utilisez les méthodes de manipulation de chemin de NSString pour obtenir les noms de fichiers et de dossiers à droite. Par exemple,

NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];

Les deux classes sont assez bien expliquées dans les documents, mais laisser un commentaire s'il y a quelque chose que vous ne comprenez pas.

Autres conseils

Il convient de noter que le déplacement d'un fichier lui-même échouera. J'avais une méthode qui a remplacé espaces par des underscores et fait le minuscule nom de fichier et renommé le fichier au nouveau nom. Fichiers avec un seul mot au nom échoueraient le changement de nom que le nouveau nom serait identique sur un système de fichiers sensible à la casse.

La façon dont je résolu c'était de faire un changement de nom en deux étapes, d'abord renommer le fichier à un nom temporaire, puis renommer le nom voulu.

Certains pseudo-code expliquant ceci:

NSString *source = @"/FILE.txt";
NSString *newName = [[source lastPathComponent] lowercaseString];
NSString *target = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];

[[NSFileManager defaultManager] movePath:source toPath:target error:nil]; // <-- FAILS

La solution:

NSString *source = @"/FILE.txt";
NSString *newName = [[source lastPathComponent] lowercaseString];

NSString *temp = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-temp", newName]];
NSString *target = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];

[[NSFileManager defaultManager] movePath:source toPath:temp error:nil];
[[NSFileManager defaultManager] movePath:temp toPath:target error:nil];

Je voulais juste rendre cela plus facile à comprendre pour un débutant. Voici tout le code:

    NSString *oldPath = @"/Users/brock/Desktop/OriginalFile.png";
NSString *newFilename = @"NewFileName.png";

NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];

NSLog( @"File renamed to %@", newFilename );

voici un exemple plus récent pour iOS, la méthode NSFileManager est un peu différent:

NSString *newFilename = [NSString stringWithFormat:@"%@.m4a", newRecording.title];

NSString *newPath = [[newRecording.localPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] moveItemAtPath:newRecording.localPath toPath:newPath error:nil];

Pour la cerise sur le dessus, une catégorie sur 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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top