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



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

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

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

是否有框架函数来实现此目的?弃用不是问题。

顺便说一句,这是反向操作的解决方案。

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

目标-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
    }
}

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
}

最新更新