将文件写入 Resources 目录

Write a file to Resources directorty

我有文件保存在Resources中,在用户第一次运行申请的时候。它将使用资源中的文件。任何其他时候应用程序应该 运行 一个已经从互联网下载的文件。 我可以从网上下载一个文件,保存到文档目录下。 我的问题是如何覆盖第一个文件上的新文件。

如果我可以写在 Resources 目录上。它会解决。

此方法returns文件路径来自文档目录

+(NSString*)filePathFromDocumentsDirectoryForFile:(NSString*)fileName
{
// Define the decumnets directory for the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString  *documentsDirectory = [paths objectAtIndex:0];
  return [NSString stringWithFormat:@"%@/%@", documentsDirectory,fileName];
}

您无法写入应用程序包。处理此问题的一种方法是检查每次读取文件是否存在于 Documents 目录中,如果不存在,则使用包中的文件。

尝试使用以下代码:

NSString *filePathInBundle = [[NSBundle mainBundle] pathForResource:@"fileName" ofType:@"file Extension here"];

NSString *filePathInDocumentDir = [@"~/Documents/filename.txt" stringByExpandingTildeInPath];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePathInDocumentDir]) {
    // use file from document directory
}else{
    // user file from bundle
}

并将数据存储在文档目录中尝试以下代码。

NSData *data = [NSData new]; //  Assign your data here
[data writeToFile:filePathInDocumentDir atomically:YES];

希望对您有所帮助。