如何将经典 HFS 路径转换为 POSIX 路径
How to convert a classic HFS path into a POSIX path
我正在阅读仍然使用 HFS 样式路径的旧文件,例如 VolumeName:Folder:File
。
我需要将它们转换成 POSIX 路径。
我不喜欢进行字符串替换,因为它有点棘手,我也不想为此任务调用 AppleScript 或 Shell 操作。
是否有框架功能可以实现?弃用不是问题。
顺便说一句,这里是 。
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
}
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
Swift
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
}
}
我正在阅读仍然使用 HFS 样式路径的旧文件,例如 VolumeName:Folder:File
。
我需要将它们转换成 POSIX 路径。
我不喜欢进行字符串替换,因为它有点棘手,我也不想为此任务调用 AppleScript 或 Shell 操作。
是否有框架功能可以实现?弃用不是问题。
顺便说一句,这里是
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
}
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
Swift
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
}
}