Domanda

Come faccio a rinominare un file, mantenendo il file nella stessa directory?

Ho una stringa contenente un percorso completo di un file, e una stringa contenente un nuovo nome di file (e nessun percorso), per esempio:

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

Lo so in merito a NSFileManager MovePath: topath: handler: metodo , ma non posso allenamento come costruire il percorso del nuovo file di ..

In sostanza sto cercando l'equivalente al seguente codice Python:

>>> 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)
È stato utile?

Soluzione

NSFileManager e NSWorkspace entrambi hanno metodi di manipolazione dei file, ma - (BOOL)movePath:(NSString *)source toPath:(NSString *)destination handler:(id)handler di NSFileManager è probabilmente la soluzione migliore. Utilizzare metodi di manipolazione percorso di NSString per ottenere i nomi di file e cartelle a destra. Ad esempio,

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

Entrambe le classi sono spiegate abbastanza bene nella documentazione, ma lasciano un commento, se c'è qualcosa che non capisci.

Altri suggerimenti

Vale la pena notare che lo spostamento di un file su se stesso fallirà. Ho avuto un metodo che ha sostituito gli spazi con sottolineature e ha fatto il nome del file in minuscolo e rinominato il file con il nuovo nome. I file con una sola parola in nome sarebbe falliscono la ridenominazione come il nuovo nome sarebbe stato identico in un file system case-insensitive.

Il modo in cui ho deciso che questo era di fare una ridenominazione in due fasi, prima rinominare il file a un nome temporaneo e quindi rinominando al nome previsto.

Alcuni pseudocodice spiegare questo:

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 soluzione:

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];

Volevo solo rendere questo più facile da capire per un principiante. Ecco tutto il codice:

    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 );

Ecco un esempio più recente per iOS, il metodo NSFileManager è un po 'diverso:

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

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

Per la ciliegina sulla cima, una categoria a 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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top