当前位置: 首页 > 知识库问答 >
问题:

尝试从捆绑复制到文档目录时出错

赏彭薄
2023-03-14

我已经在应用程序中添加了一个sqlite文件,并试图将其从bundle复制到documents目录。我还将sqlite添加到了target应用程序中。下面是我用来复制文件的代码:

NSString *destination = [[[Utils applicationDocumentsDirectory] absoluteString] stringByAppendingString:@"myapp.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:destination]) {
        NSString *source = [[NSBundle mainBundle] pathForResource:@"myapp" ofType:@"sqlite"];
        NSError *error = nil;
        [fileManager copyItemAtPath:source toPath:destination error:&error];
        if (error) {
            //
        }
    }

[Utils applicationDocumentsDirectory]的代码:

+ (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

Error domain=nscocoaerrordomain code=4“文件”myapp.sqlite“不存在。”userInfo={nsSourceFilePatherRokey=/users/harikrishnant/library/developer/coreSimulator/devices/8e531314-F1AE-417F-8e99-7aa92967cdc9/data/containers/bundle/application/0a710929-475D-457C-8d2D-C2BBEB6B92/myapp.app/myapp.sqlite,nsUserStringVariant=(Copy),nsDestinationFilePath=file:

我使用terminal检查了以下路径,发现sqlite文件实际上存在于应用程序包中:

/用户/Harikrishnant/库/开发人员/CoreSimulator/设备/8E531314-F1AE-417F-8E99-7AA92967CDC9/Data/容器/Bundle/应用程序/0A710929-475D-457C-8D2D-C2F2BBEB6B92/myapp.app/myapp.sqlite

但我还是得到了这个错误。我什么都试过了。我甚至清理了构建文件夹,重新安装了应用程序,它仍然没有工作。这里会有什么问题?如何解决?

共有1个答案

齐夕
2023-03-14

你的代码几乎是正确的。这条线有两个缺陷:

NSString *destination = [[[Utils applicationDocumentsDirectory] absoluteString] stringByAppendingString:@"myapp.sqlite"];

AbsoluteString的使用不正确。这将给出一个文件URL,格式文件://path/to/documents/。您需要使用path方法从nsurl获取文件路径(而不是文件URL)。

然后需要将文件名正确地追加到路径中。您需要使用StringByAppendingPathComponent:而不是StringByAppendingString:

这一行应为:

NSString *destination = [[[Utils applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"myapp.sqlite"];
 类似资料:
  • 我得到错误,而试图通过捆绑通过数组列表请帮助 JAVAlang.RuntimeException:无法启动活动组件信息{com.sandyzfeaklab.Breakdown_app/com.sandyzfeaklab.Breakdown_app.Data_input}:java。lang.NullPointerException:尝试调用虚拟方法“java”。木卫一。可序列化的android。操

  • 问题内容: 我最近开发了一个应用程序,并创建了jar文件。 我的课程之一创建了一个输出目录,并使用其资源中的文件填充该目录。 我的代码是这样的: 不幸的是,这不起作用。 我没有运气就尝试了以下方法: 使用Streams解决其他类上的类似问题,但不适用于dirs。代码类似于 http://www.exampledepot.com/egs/java.io/CopyFile.html 使用创建文件模板

  • 我正在使用QT,我无法找到如何将文件从一个目录复制到另一个目录?我怎样才能做到这一点?

  • 无法弄清楚为什么我得到一个文件未找到错误,当我运行一个协议命令来生成相关的go文件。 问题:在尝试从不同目录导入原型文件时,试图找出合适的原型命令是什么。我在GoLand中将原型路径设置为 结构 歌曲原型 Search.proto 创建文件: 错误: