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

时间:2010-01-07 22:54:59

标签: iphone nsbundle

对不起,今天愚蠢的问题2。是否可以确定App Bundle中是否包含文件?我可以访问文件没问题,即

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

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

此致

戴夫

5 个答案:

答案 0 :(得分:68)

[[NSFileManager defaultManager] fileExistsAtPath:pathAndFileName];

答案 1 :(得分:15)

这段代码对我有用......

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

希望它会帮助某人......

答案 2 :(得分:4)

如果资源不存在,

pathForResource将返回nil。使用NSFileManager再次检查是多余的。

<强>的OBJ-C:

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

Swift 4:

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

答案 3 :(得分:3)

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

答案 4 :(得分: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()
相关问题