【问题标题】:Separate filename from file extension Cocoa?将文件名与文件扩展名 Cocoa 分开?
【发布时间】:2011-09-04 04:22:16
【问题描述】:

我正在使用writeToFile:atomically: 方法将一些加密数据写入文本文件。问题是,它需要保存的文件必须是用户加密的文件,并带有我选择的扩展名。这是我目前所拥有的:

[encryptedData writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"] 
    stringByAppendingPathComponent:@"encryptedfile.txt.kry"] atomically:YES];
                                           ^//fileName here

如您所见,加密文件名被硬编码为 encryptedfile.txt.kry。但是假设用户选择文件“test.avi”进行加密,写入桌面的加密文件应该命名为test.avi.kry。所以应该有 ofType:,就像在 NSBundle 中一样。我知道这里有一些我可以使用的 NSString 方法,但已经忘记了。

谢谢!

【问题讨论】:

    标签: cocoa filenames nsbundle writetofile


    【解决方案1】:

    你不能只将 .kry 附加到文件名上吗?

    如果你有路径,并且只想要文件名,你可以使用- (NSString *)lastPathComponent:

    NSString *filename = [filePath lastPathComponent];
    [encryptedData writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"] 
        stringByAppendingPathComponent:[filename stringByAppendingString:@".kry"] atomically:YES];
    

    如果你想要不带扩展名的文件名,你可以使用- (NSString *)stringByDeletingPathExtension:

    NSString *filename = [[filePath lastPathComponent] stringByDeletingPathExtension];
    

    【讨论】:

    • 我不小心放错了a']',这解释了为什么它最初不起作用。这么笨的我忘记了这样的事情,永远不会忘记!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-12-19
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多