【问题标题】:IOS: copy a file in documents folderIOS:复制文件文件夹中的文件
【发布时间】:2011-07-01 07:58:15
【问题描述】:

在我的项目中,我有两个文件 .txt(在 Resources 文件夹中),如何将它们复制到文档文件夹中?

【问题讨论】:

    标签: ios xcode bundle


    【解决方案1】:

    txtFile 从资源复制到文档(如果不存在)。

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"txtFile.txt"];
    
    if ([fileManager fileExistsAtPath:txtPath] == NO) {
        NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
        [fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
    }
    

    如果你想每次都覆盖,那么试试这个:

    if ([fileManager fileExistsAtPath:txtPath] == YES) {
        [fileManager removeItemAtPath:txtPath error:&error];
    }
    
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"txtFile" ofType:@"txt"];
    [fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
    

    【讨论】:

    • 在这种情况下,如果文件已经存在,则使用 removeItemAtPath:error: 删除它
    • 好的,如果我想对我的文件进行更改,我会修改“资源文件夹”中的文件,并在我替换文档文件夹中的这个文件后,如您所示...好吗?
    • 如果您更改了资源中的文件,则在运行第二个代码后应该覆盖文档中的文件。它是否有效?你检查了吗?
    • 另一件事:这样我的文件在文档文件夹中,没关系。现在想读这个文件,请问怎么读?
    【解决方案2】:

    斯威夫特 3

    文件的代码是否存在,如果不存在则复制。

    func CheckFileisExistOrNot(strPath:String) {
        let filemgr = FileManager.default
        if !filemgr.fileExists(atPath: strPath) {
            let resorcePath = Bundle.main.path(forResource: "\(Global.g_databaseName)", ofType: ".db")
            do {
                try filemgr.copyItem(atPath: resorcePath!, toPath: strPath)
            }catch{
                print("Error for file write")
            }
        }
    }
    

    【讨论】:

      【解决方案3】:
      NSFileManager *fileManager = [NSFileManager defaultManager];
      NSError *error;
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
      NSString *documentsDirectory = [[paths objectAtIndex:0]stringByAppendingString:@"csvfile"];
      
      NSString *txtPath = [documentsDirectory stringByAppendingPathComponent:@"sample.csv"];
      
      if ([fileManager fileExistsAtPath:txtPath] == NO) {
          NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@".csv"];
          [fileManager copyItemAtPath:resourcePath toPath:txtPath error:&error];
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-18
        • 1970-01-01
        • 2012-07-12
        相关资源
        最近更新 更多