如何确定应用程序包中是否存在文件?

52

抱歉,今天又问了一个愚蠢的问题。是否有可能确定文件是否包含在应用程序包中?我可以轻松访问文件,例如:

对不起,今天又问了一个愚蠢的问题。是否有可能确定文件是否包含在应用程序包中?我可以轻松访问文件,例如:

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];

但是我无法弄清楚如何首先检查文件是否存在。

敬礼

Dave


4
如果文件不存在,[[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"] 将返回NULL,因此我通常只需检查 if (pathAndFileName != NULL) { //file exists } 就行了。 - jsherk
你也可以不用编码来完成它。请查看我在另一个论坛上的帖子:http://forums.macrumors.com/threads/xcode-6-how-do-i-view-all-files-in-my-main-bundle.1904024/ - user749127
@moonman239 我需要进行的检查需要在代码中完成,因为我正在使用缓存的缩略图像预加载应用程序,以便初始运行速度更快。我有另一个线程来下载新的数据文件。当数据被显示时,应用程序需要检查图像是否在捆绑包中(预加载的缓存图像)。如果没有,则从服务器检索图像并保存到磁盘缓存中。希望这样说得清楚。 - Magic Bullet Dave
@MagicBulletDave 我还是不理解。缓存的图片是随着应用程序一起下载的吗?如果是的话,那么理论上代码就没有必要检查图片是否存在——应用程序可以假定它已经存在。 - user749127
这是一个通用算法。该应用程序附带一个以plist形式的数据文件。每行数据都有一个缩略图像。在首次加载时,所有内容都在捆绑包中,因此可以直接从中显示。定期下载新的plist(其中包含一些现有数据和一些新数据)。现有数据的图像将在捆绑包中,新数据的图像需要下载,然后缓存到磁盘上。因此,事件链是:首先查找捆绑包,然后是磁盘缓存,最后如果仍然没有图像,则尝试从服务器下载。有意义吗? - Magic Bullet Dave
5个回答

70
[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];

糟糕!谢谢 Rob,我一直在使用那个来处理文档目录中的文件!已经很晚了。再次感谢。 - Magic Bullet Dave
5
根据这个答案,即使是苹果公司也建议实际尝试一个操作(例如加载文件或创建目录),检查错误并优雅地处理任何错误,而不是事先尝试弄清楚操作是否成功。 - gregoltsov

16

这段代码对我很有效...

NSString *pathAndFileName = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName])
{
    NSLog(@"File exists in BUNDLE");
}
else
{
    NSLog(@"File not found");
}

希望这能帮助到某些人...


10

如果资源不存在,pathForResource将返回nil。再次使用NSFileManager进行检查是多余的。

Obj-C:

 if (![[NSBundle mainBundle] pathForResource:@"FileName" ofType:@"plist"]) {                                              
      NSLog(@"The path could not be created.");
      return;
 }

Swift 5:

 guard Bundle.main.path(forResource: "FileName", ofType: "plist") != nil else {
      print("The path could not be created.")
      return
 }

4
NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"filename"];
    if(![fileManager fileExistsAtPath:path])
    {
        // do something
    }

4
这是查看文档目录而不是应用程序捆绑包。 - richy

1

和@Arkady一样,但使用Swift 2.0:

首先,在mainBundle()上调用一个方法来帮助创建资源的路径:

guard let path = NSBundle.mainBundle().pathForResource("MyFile", ofType: "txt") else {
    NSLog("The path could not be created.")
    return
}

然后,调用defaultManager()上的一个方法来检查文件是否存在:

if NSFileManager.defaultManager().fileExistsAtPath(path) {
    NSLog("The file exists!")
} else {
    NSLog("Better luck next time...")
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接