Переименовать файл в Какао?
-
22-08-2019 - |
Вопрос
Как мне переименовать файл, сохранив его в том же каталоге?
У меня есть строка, содержащая полный путь к файлу, и строка, содержащая новое имя файла (без пути), например:
NSString *old_filepath = @"/Volumes/blah/myfilewithrubbishname.avi";
NSString *new_filename = @"My Correctly Named File.avi";
Я знаю о NSFileManager movePath: toPath: обработчик: метод, но я не могу понять, как построить путь к новому файлу.
По сути, я ищу эквивалент следующего кода 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)
Решение
У NSFileManager и NSWorkspace есть методы манипулирования файлами, но у NSFileManager - (BOOL)movePath:(NSString *)source toPath:(NSString *)destination handler:(id)handler
вероятно, ваш лучший выбор.Используйте методы манипулирования путями NSString, чтобы получить правильные имена файлов и папок.Например,
NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] movePath:oldPath toPath:newPath handler:nil];
Оба класса довольно хорошо объяснены в документации, но оставьте комментарий, если вам что-то непонятно.
Другие советы
Стоит отметить, что переместить файл самому себе не удастся.У меня был метод, который заменял пробелы подчеркиваниями, делал имя файла строчными и переименовывал файл в новое имя.Файлы, содержащие только одно слово в имени, не смогут быть переименованы, поскольку новое имя будет идентичным в файловой системе без учета регистра.
Я решил эту проблему, выполнив двухэтапное переименование: сначала переименовав файл во временное имя, а затем переименовав его в предполагаемое имя.
Некоторый псевдокод, объясняющий это:
NSString *source = @"/FILE.txt";
NSString *newName = [[source lastPathComponent] lowercaseString];
NSString *target = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newName];
[[NSFileManager defaultManager] movePath:source toPath:target error:nil]; // <-- FAILS
Решение:
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];
Я просто хотел сделать это проще для понимания новичку.Вот весь код:
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 );
вот более свежий пример для iOS, метод NSFileManager немного отличается:
NSString *newFilename = [NSString stringWithFormat:@"%@.m4a", newRecording.title];
NSString *newPath = [[newRecording.localPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newFilename];
[[NSFileManager defaultManager] moveItemAtPath:newRecording.localPath toPath:newPath error:nil];
В качестве вишенки сверху — категория в 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