如何将经典HFS路径转换为POSIX路径

问题描述 投票:0回答:2

我正在阅读仍使用HFS样式路径的旧文件,例如VolumeName:Folder:File

我需要将它们转换为POSIX路径。

我不喜欢做字符串替换,因为它有点棘手,我也不想为此任务调用AppleScript或Shell操作。

是否有框架功能来实现这一目标?弃用不是问题。

顺便说一句,这是一个solution for the inverse operation

objective-c swift macos cocoa core-foundation
2个回答
1
投票

Obj-C和Swift中的解决方案作为NSString / String的类别/扩展。不可用的kCFURLHFSPathStyle风格以与链接问题相同的方式被规避。

Objective-C的

@implementation NSString (POSIX_HFS)

    - (NSString *)POSIXPathFromHFSPath
    {
        NSString *posixPath = nil;
        CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)self, 1, [self hasSuffix:@":"]); // kCFURLHFSPathStyle
        if (fileURL)    {
            posixPath = [(__bridge NSURL*)fileURL path];
            CFRelease(fileURL);
        }

        return posixPath;
    }

@end

迅速

extension String {

    func posixPathFromHFSPath() -> String?
    {
        guard let fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                                          self as CFString?,
                                                          CFURLPathStyle(rawValue:1)!,
                                                          self.hasSuffix(":")) else { return nil }
        return (fileURL as URL).path
    }
}

1
投票

CFURLCopyFileSystemPath()的“逆向”操作是CFURLCreateWithFileSystemPath()。与引用的问答类似,您可以从原始枚举值创建路径样式,因为CFURLPathStyle.cfurlhfsPathStyle已弃用且不可用。例:

let hfsPath = "Macintosh HD:Applications:Xcode.app"
if let url = CFURLCreateWithFileSystemPath(nil, hfsPath as CFString,
                                           CFURLPathStyle(rawValue: 1)!, true) as URL? {
    print(url.path) // /Applications/Xcode.app
}
© www.soinside.com 2019 - 2024. All rights reserved.