IOS:复制文档文件夹中的文件

Cra*_*Dev 41 xcode bundle ios

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

tas*_*oor 116

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];
}
Run Code Online (Sandbox Code Playgroud)

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

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];
Run Code Online (Sandbox Code Playgroud)


Ile*_*esh 5

斯威夫特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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)