IOS: copy a file in documents folder

前端 未结 3 1712
北海茫月
北海茫月 2020-11-27 15:00

In my project I have two file .txt (in Resources folder), how can I copy them inside documents folder?

相关标签:
3条回答
  • 2020-11-27 15:51

    Swift 3

    code for file is exist or not, if not then copy.

    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")
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 16:04

    Copies txtFile from resource to document if not already present.

    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 you want to overwrite every time then try this:

    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];
    
    0 讨论(0)
  • 2020-11-27 16:05
    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];
    
    0 讨论(0)
提交回复
热议问题