문제

파일 이름을 동일한 디렉토리에 보관하고 파일 이름을 어떻게 바꾸겠습니까?

파일의 전체 경로가 포함 된 문자열과 예를 들어 새 파일 이름 (및 경로 없음)이 포함 된 문자열이 있습니다.

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

나는 nsfileManager의 것에 대해 알고 있습니다 MovePath : Topath : Handler : 방법이지만 새 파일의 경로를 구성하는 방법을 운동 할 수 없습니다 ..

기본적으로 나는 다음 파이썬 코드와 동등한 것을 찾고 있습니다.

>>> 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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top